Applescript equivalent of "continue"?
-- Or you could use different strategy: use the loop to loop, and do the conditional logic in a handler, like so:
set aList to {"1", "2", "3", "4", "5"}
repeat with anItem in aList
doConditionalWork(anItem as string)
end repeat
on doConditionalWork(value)
if value = "3" then return
display dialog value
end doConditionalWork
set aList to {"1", "2", "3", "4", "5"}
repeat with anItem in aList -- # actual loop
try
set value to item 1 of anItem
if value = "3" then error 0 -- # simulated `continue`
log value
end try
end repeat
This will still give you the "exit repeat" possibillity
set aList to {"1", "2", "3", "4", "5"}
repeat with anItem in aList -- # actual loop
try -- # needed to simulate continue
set value to item 1 of anItem
if value = "3" then continueRepeat -- # simulated `continue` throws an error to exit the try block
log value
on error e
if e does not contain "continueRepeat" then error e -- # Keeps error throwing intact
end try
end repeat
Based on the try block based approach above but reads slightly better. Of course, since continueRepeat is not defined an error will be thrown which causes the rest of the try block to be skipped.
To keep error throwing intact include the on error clause that throws any unexpected error.
After searching for this exact problem, I found this book extract online. It exactly answers the question of how to skip the current iteration and jump straight to the next iteration of a repeat
loop.
Applescript has exit repeat
, which will completely end a loop, skipping all remaining iterations. This can be useful in an infinite loop, but isn't what we want in this case.
Apparently a continue
-like feature does not exist in AppleScript, but here is a trick to simulate it:
set aList to {"1", "2", "3", "4", "5"}
repeat with anItem in aList -- # actual loop
repeat 1 times -- # fake loop
set value to item 1 of anItem
if value = "3" then exit repeat -- # simulated `continue`
display dialog value
end repeat
end repeat
This will display the dialogs for 1, 2, 4 and 5.
Here, you've created two loops: the outer loop is your actual loop, the inner loop is a loop that repeats only once. The exit repeat
will exit the inner loop, continuing with the outer loop: exactly what we want!
Obviously, if you use this, you will lose the ability to do a normal exit repeat
.