4.3. The repeat while Statement

You use the repeat while statement to repeat a set of statements while a specified condition is true. In the following Try It Out, you see how you can use the repeat while to count to 10.

4.3.1.

4.3.1.1. Try It Out: Counting from 1 to 10

You can use the following program to count to 10 by using repeat while.

  1. Start up Script Editor and type the following program:

    -- Count from 1 to 10: repeat while
    
    set n to 1
    repeat while n = 10
    log n
        set n to n + 1
    end repeat
  2. Click the Event Log tab and run the program. If you look at the Event Log pane, you see the following results displayed:

    (*1*)
        (*2*)
        (*3*)
        (*4*)
        (*5*)
        (*6*)
        (*7*)
        (*8*)
        (*9*)
        (*10*)
4.3.1.2. How It Works

Here is the general format of the repeat while statement:

repeat while Boolean-expression
    statement
    statement
    ...
end repeat

When this loop begins execution, Boolean-expression is evaluated. If the result of the evaluation is true, the statements that follow up to the end repeat are executed. If Boolean-expression is false, the loop is immediately terminated, and execution continues in the program with whatever statements follow the end repeat. In other words, the body of the loop is repeatedly executed as long as Boolean-expression is true.

In the Try It Out example, the variable n is initially set to 1 with this statement:

set n to 1

The repeat while loop follows next:

repeat while n = 10
    log n
    set n to n + 1
end repeat

This loop is executed as long as the value of the expression

n ≥ 10 ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.