Previous Book Contents Book Index Next

Inside Macintosh: AppleScript Language Guide / Part 2 - AppleScript Language Reference
Chapter 7 - Control Statements


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 way

they 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 repeat
The following Repeat statement performs the same actions while a specific condition is true:

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 tell
You 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 tell
More 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 tell
Note 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. 10
The line

repeat with n from 1 to 10
specifies n 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 reaches 10, AppleScript exits the loop.
The expression n 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."


Previous Book Contents Book Index Next

© Apple Computer, Inc.
13 JUL 1996