Loops

Repeat forever

Please remember an exit statement, or it is not going to end well for you.

put 0 into myVar
repeat forever
 add 1 to myVar
 put myVar
 if myVar = 5 then
 exit repeat
 end if
end repeat
// outputs 12345

Repeat … until

put 0 into myVar
repeat until myVar = 6
 put myVar
 add 2 to myVar 
end repeat
// outputs 024

Repeat … while

put 0 into myVar
repeat while myVar < 6
 put myVar
 add 3 to myVar
end repeat
// outputs 03

Repeat … for n times

put 0 into myVar
repeat for 5 times
 add 1 to myVar
 put myVar
end repeat
// outputs 012345

Repeat … with

repeat with myVar = 1 to 5
 put myVar
end repeat
// outputs 12345
repeat with myVar=1 to 10 step 5
 put myVar & comma
end repeat
// outputs 1,6,11,
repeat with myVar=5 down to 1
 put myVar & comma
end repeat
// 5,4,3,2,1,
repeat with myVar=5 down to 1 step -2
 put myVar & comma
end repeat
// outputs 5,3,1,

Repeat … for each

put "apple,banana,orange" into myVar
repeat for each item fruit in myVar
 put fruit & comma
end repeat
// outputs apple,banana,orange,

Leave a Reply