Using labels to break from nested loops
I haven't seen to many people actually using labels in ActionScript 3 either among the evangelists or in tutorials. Actually the first time I saw it was in the Essential Guide to Flash Games book by guys from 8BitRocket in an example showing collision detection between a player and enemies. In this post I'm showing an example use case.
Imagine you have two arrays and two "for" loops going through them. And in the nested loop you have condition that checks something and if the result is "true" you want to escape both loops. You could do that using "return" (in case your function is returning void) but this just exits your function and if there are other lines of code following the "for" loops they wan't be executed. So breaking with labels is an alternative that you are looking for.
Look at this example and trace:
Trace output:
---- 0 0 0 1 0 2 ---- 1 0 1 1 ++breaking ---- 2 0 2 1 2 2 some other tasks
You can see that in this case the "break" breaks just the nested "for" and continues with a next iteration of the primary loop. But see what happens if we give a label to the primary "for" and then refer it in the "break" statement:
var primaryArray:Array = [0, 1, 2]; var secondaryArray:Array = [0, 1, 2]; primary: for (var i:int = 0; i < primaryArray.length; i++) { trace('----'); for (var j:int = 0; j < secondaryArray.length; j++) { if (i == 1 && j == 2) { trace('++breaking'); break primary; } trace(i, j); } } trace('some other tasks');
then the trace looks like this:
---- 0 0 0 1 0 2 ---- 1 0 1 1 ++breaking some other tasks
So you see that both "for" loops are stopped but Flash continues executing remaining lines of your function.


Comments