views:

1280

answers:

4

Hi, I have a simple 'repeat with' in an AppleScript, and would like to move on to the next item in the "repeat" conditionally. Basically I'm looking for something similar to "continue" (or break?) in other languages.

I'm not well versed in AppleScript but I have found it useful a few times now.

+1  A: 

have you tried

exit repeat

source: http://www.mactech.com/articles/mactech/Vol.20/20.12/RepeatLoops/index.html

Josh

Josh
+1  A: 

There isn't "continue", but "exit repeat" does the same thing only from a different direction...

set mList to {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}

set the item_count to the number of items in mList
repeat with i from 1 to the item_count
    set this_item to item i of mList

    if this_item is "5" then
     exit repeat
    end if

end repeat

return i // return = 5
Philip Regan
Will that still loop over 6-9?
qbn
"Will that still loop over 6-9?" No. "exit repeat" causes the loop to stop on the condition presented in the "if" clause. In the example I gave, the loop variable is returned *outside* of the loop, effectively where the loop stopped.
Philip Regan
+6  A: 

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.

Tom Lokhorst
+1 Clever workaround to a stupid oversight in the language.
Carl Manaster
The code above won't compile because comments in applescript are -- not #
alexy13