repeat with {loop variable} in {list} end [repeat] |
|
Syntax
Repeat with listVar in myList
(* code statements *)
end repeat
Description
This variation of the repeat with statement
iterates over a list of values, storing the
current value in the loop variable. Once the last
item in the list has been
stored in the loop variable, the statement terminates and code
execution resumes after end repeat. If you have to
examine a list's contents, this
statement is a crucial part of your code. You can also use the
exit statement inside this repeat
with statement to stop executing code inside the loop.
After any call to exit, code execution resumes
after the end repeat part. You do not have to
declare the loop variable in any way; AppleScript creates this
temporary reference variable for you. You can also get the loop
variable's value later in the script, after the
repeat loop has completed executing. The value will be a reference to
the last item in the list:
item 6 of {"Each", "word", "on", "a", "different", "line"}
Using this form of repeat loop, you can get inaccurate results if the
script is trying to compare the value of the loop variable with
another value (such as a string or
integer). Instead, one of our technical reviewers
recommends that you use syntax such as:
set booleanVar to ((contents of loopVar) equals 1)" (* note the "contents of" part *)
The value used in the part of the statement following the
in reserved word must be a
list.
Examples
This code takes each of the items of a list and
concatenates them to a string, which is then
displayed to the user:
set theString to "Each word on a different line"
set theList to words of theString -- returns a list of words
set displayString to "" -- initialize this string
repeat with wd in theList
set displayString to displayString & return & wd
end repeat
display dialog displayString
wd as string -- this will return "line"
AppleScript does not destroy the loop variable (wd
in the prior example) after the repeat loop is finished. Getting the
value of wd in the last example, after the
repeat with statement has done its job, returns:
item 6 of {"Each", "word", "on", "a", "different", "line"}
|