The AppleScript for loop (and while loop) examples

AppleScript for loop FAQ: How do I use an AppleScript for loop? (Also, how do you use an AppleScript while loop?)

This is actually a bit of a trick question, as there is no AppleScript for loop or while loop syntax. Instead you use the AppleScript repeat command, as shown in the following examples.

AppleScript `for` loop examples (“repeat”)

Where you might expect an AppleScript for loop to iterate over a list, you use the AppleScript repeat with syntax:

set myList to {"Hello", "Goodbye", "I must be going"}
repeat with theItem in myList
  say theItem
end repeat

If you want to repeat an AppleScript loop a number of times, you can use the AppleScript repeat n times syntax:

repeat 3 times
  say "hello"
end repeat

AppleScript `while` loop examples

Finally, where you might expect to find an AppleScript while loop, you use the repeat while syntax, like this:

set theName to ""
repeat while theName = ""
  display dialog "Dude, enter your name:" default answer ""
  set theName to text returned of result
  say theName
end repeat

AppleScript ‘for’ loop and ‘while’ loop examples

I hope these AppleScript for loop and while loop examples have been helpful. For more information on AppleScript lists, see my collection of AppleScript list examples.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.