Breaking a loop early.

BlitzMax Forums/BlitzMax Beginners Area/Breaking a loop early.

Ryan Burnside(Posted 2008) [#1]
I was just wondering how to break a loop early if a result is found before the looping operation is compleated?

I'm using a for loop to search but I would like to break out of the for loop if the result is found before the end of the for loop.


SebHoll(Posted 2008) [#2]
Use the Exit command.

Here is the example from the docs:
Rem
Exit causes program flow to exit the enclosing While, Repeat or For loop.
End Rem

Repeat
	Print n
	n:+1
	If n=5 Exit
Forever



Ryan Burnside(Posted 2008) [#3]
Ahhh ok thanks. I thought that was a command to close the program.


SebHoll(Posted 2008) [#4]
I thought that was a command to close the program.

That's what End does... ;-)


Zethrax(Posted 2008) [#5]
Another loop command to be aware of is the Continue command, which basically allows you to force the loop to stop processing the current loop iteration and jump to the start of the next iteration.

In Strict and Superstrict modes, both Exit and Continue can have a label parameter which allows them to jump to a specific point in the program, defined by the label used. For Exit this allows you to jump out of multiple nested loops.

From the docs:-

Exit and Continue
The Exit command can be used to exit from a While, Repeat or For loop. The loop will be terminated, and program flow will be transferred to the first command after the loop.

The Continue command can be used to force a While, Repeat or For loop to resume execution from the 'top' of the loop, skipping any statements remaining in the loop.

Both Exit and Continue may be followed by an optional identifier. This identifer must match a previously declared loop label, which allows you to exit or continue a specific loop, not necessarily the 'nearest' loop.

To declare a loop label, use the syntax #Identifier immediately preceding a While, Repeat or For loop. For example, this program will exit both loops when k and j both equal 5:

Strict
Local k,j
#Label1 'loop label
For k=1 To 4
#Label2 'another loop label (unused in this example)
For j=1 To 4
Print k+","+j
If k=3 And j=3 Exit Label1
Next
Next

Note that loop labels are only available in strict mode. In non-strict mode, use Goto instead.