Repeat Statements
Repeat statements are used to create loops, or groups of repeated statements, in scripts. There are several types of Repeat statements, which differ in the waythey specify when the repetition stops.
For example, the following Repeat statement performs the same action a specified number of times:
repeat 2 times beep end repeatThe following Repeat statement performs the same actions while a specific condition istrue
:
tell application "Scriptable Text Editor" set numberOfWindows to (count windows) repeat while numberOfWindows > 0 close front window set numberOfWindows to (count windows) end repeat end tellYou can also specify an infinite loop, which is a Repeat statement that does
not specify when the repetition stops. You can use an Exit statement within
an infinite loop or any other Repeat statement to immediately exit the
Repeat statement.Here's an example of a Repeat statement with an Exit statement:
tell application "Scriptable Text Editor" set numberOfWindows to (count windows) set i to 1 repeat if i > numberOfWindows then exit end if print window i set i to i + 1 end repeat end tellMore elaborate forms of the Repeat statement use looping variables that you can refer to in the body of the loop. Here's an example:
tell application "Scriptable Text Editor" set contents of front window to "" set selection to "David Numberman's Top Ten Numbers for Lists " repeat with n from 1 to 10 copy (n as string & ". " & n as string & " " ) to n select end of front window set selection to n end repeat end tellNote that two of the strings in the preceding statement include a return character. These are valid strings even though the surrounding quotation marks are on different lines within the statement. Running the preceding statement results in the following text:
David Numberman's Top 10 Numbers for Lists 1. 1 2. 2 3. 3 4. 4 5. 5 6. 6 7. 7 8. 8 9. 9 10. 10The line
repeat with n from 1 to 10specifiesn
as the looping variable, a variable that controls the number
of iterations.At the beginning of each iteration, AppleScript adds 1 to the value of
n
. When the value of the looping variable reaches10
, AppleScript exits the loop.
The expressionn as string
coerces an integer into a string, while the & (concatenation) operator joins two strings to make a single string. For more information about operators and coercing values, see Chapter 6, "Expressions."