AppleScript tip: repeat/while syntax

By Alvin J. Alexander, devdaily.com

Instead of using a keyword like "while" to create loops, AppleScript uses the "repeat" keyword to create loops. There are several versions of this syntax, as follows.

Repeat X times

repeat 3 times
  say "Hello"
end repeat

Repeat while

Here's a slightly different version of that loop, using the "repeat while" syntax:

set i to 3
repeat while i > 0
  say "Hello"
  set i to i - 1
end repeat

Repeat until

And here's the same AppleScript example using the "repeat until" syntax:

set i to 3
repeat until i = 0
  say "Hello"
  set i to i - 1
end repeat

Repeat with A from Y to Z

Here's a little different "repeat" syntax:

repeat with i from 1 to 3
  say "Hello"
end repeat

Repeat with A in {list}

To wrap it up, here's one more example of the "repeat" syntax, first using numbers in a list:

repeat with i in {1, 2, 3}
  say "Hello"
end repeat

Or, if you prefer something slightly more useful:

repeat with i in {"Hello", "I", "must", "be", "going"}
  say i
end repeat

devdaily logo