Exiting loops

There may be occasions when you want to break out of a program loop based on certain events taking place or some conditions being met. As an example imagine a do loop being used while in a level. If the player completed a level then you may want to exit the loop and move onto the next block of code that handles the high score. This behaviour can be accomplished by using the exit keyword and can be applied to any loop.

The program that follows declares four different counter variables, each of which is incremented in different loops. The first four loops have if statements to check whether these variables have reached a value of 5. If they have then the exit keyword is used to break out of the loop allowing the program to continue with code that follows. Finally there's a doloop that displays the values of the counters on screen.


counterA as integer = 0 counterB as integer = 0 counterC as integer = 0 counterD as integer = 0
repeat if counterA = 5 exit endif
counterA = counterA + 1 until counterA = 10
for i = 1 to 10 if i = 6 exit endif
counterB = counterB + 1 next i
while counterC < 10 if counterC = 5 exit endif
counterC = counterC + 1 endwhile
do if counterD = 5 exit endif
counterD = counterD + 1 loop
do print ( counterA ) print ( counterB ) print ( counterC ) print ( counterD )
sync ( ) loop