Exiting loops early
 

There are three ways to exit a loop prematurely. The first (and the one which would be cleaner) is to include some provision in the loop expression for exiting the loop. This could take the form of using another variable in the expression and combining it with the main loop expression using logical operators such as AND or OR.
Code quit.w=0 : i.w=0
While i < 5 AND quit=0
If i=4
NPrint "Quitting loop..."
quit=1
Else
NPrint "Counting... ", i
EndIf i+1
Wend

; And just to show the same thing with a different loop type
i=0 : quit=0
Repeat

If i=4
NPrint "Quitting loop..."
quit=1
Else
NPrint "Counting... ", i
EndIf i+1
Until i=10 OR quit=1

MouseWait
End

Of course, this is not always possible, e.g. in For...Next loops. Another possibility would be to change the value of the parts of the loop expression so that the loop terminates. For example, you could set the value of the variable in a For loop to the value of the second expression, which would cause the loop to end. Examples of these are shown below:

Code ; Exiting a For...Next loop by changing the value of the loop variable
For i.w=0 To 10
NPrint "First loop, counting: ",i
; We will quit this for loop when the count has reached 5
If i=5 Then i=10
Next

; Exiting another type of loop using the loop expression as is
i = 0
Repeat

NPrint "Loop2, counting: ",i
i=i+1
If i=7
NPrint "Exiting loop"
i = 10
EndIf
Until i=10

MouseWait
End

The final possibility is to use the Pop command. This makes the program "forget" about the current loop, but it also means that you must jump past the command which is used to end the loop (and this will be described on the next page). The format of the Pop command is:

Pop <Loop type>
Where <Loop type> can be Gosub, For, Select, If, While or Repeat. Actually, you only need to use Pop with the first three of those loop types, but no harm will come from using it with the last three (which have been included for completeness anyway). Full examples for the Pop command are given on the next page.


Previous: Nested loops Programming contents Next: Jumpin' around


News | Introduction | Search | List/Forum/IRC Webring | Contact
Installation | Troubleshooting | Programming | Archives | Links
Return to programming main
Page last modified: 6th February 2002