4.2. The repeat with Statement

Two different versions of the repeat with statement are used. The first one repeats a set of statements a specified number of times; it is illustrated in the following Try It Out. The second version sequences through the elements in a list; it is described later in this chapter.

4.2.1.

4.2.1.1. Try It Out: Counting from 1 to 10

To use the repeat with statement to count from 1 to 10, follow these steps:

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

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

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

Here is the general format of the repeat with...from...to statement:

repeat with loopvar from init-expr to end-expr
    statement
    statement
    ...
end repeat

Execution of the repeat with...from...to proceeds according to the following steps:

  1. The integer expression init-expr is evaluated and assigned to the variable loopvar. The terminating integer expression end-expr is also evaluated.

  2. The value of loopvar is compared to the value of end-expr. If the former is greater than the latter, the loop is immediately terminated. Execution then continues with whatever statement follows the end repeat.

  3. The statements that immediately follow the repeat, up to the end repeat, are executed.

  4. The value of the variable loopvar is incremented by 1.

  5. The process ...

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.