Hi There, So many of us use loops for a vast array of things, sometimes though you’ll want to stop a loop from executing further.
So the answer to the problem? the ‘break’ statement!
The break statement stops flash from executing the rest of the loop that the break is executed within.
Consider this loop:
for(var i:int = 0; i<10; i++)
{
for(var j:int = 0; j<10; j++)
{
trace(i, j);
if(j==5 && i==5)
{
break;
}
}
}
So we want to find if both i & j equal 5, when we do we want it to stop. But wait a minute that break will only work on the loop its contained within so our output looks like this:
i j 0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4
5 5 <- this is where our break statement kicks in. Notice how j stops execution but i continues afterward.
6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 7 0 7 1 7 2 7 3 7 4 7 5 7 6 7 7 7 8 7 9 8 0 8 1 8 2 8 3 8 4 8 5 8 6 8 7 8 8 8 9 9 0 9 1 9 2 9 3 9 4 9 5 9 6 9 7 9 8 9 9
Damn theres a load of extra work that could be avoided. The answer to that is the ‘label’.
Basically a label is a unique identifier given to a loop, which you can reference to with the break statement.
Consider our loop again but making use of a label:
myLoop: for(var i:int = 0; i<10; i++)
{
for(var j:int = 0; j<10; j++)
{
trace(i, j);
if(j==5 && i==5)
{
break myLoop;
}
}
}
Using the label (“myLabel”) you can see that we target the main loop from the sub loop. This is what the new output looks like:
0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4
5 5 <- Ending our main loop properly! woo
This method can be used on any loop in the same way as described here. Very handy for those complex array’s or procedural processes
Peace
Bill



