ActionScript 3.0: Named Loops
April 9th, 2008 Posted in ActionScriptOne of the benefits of working with other experienced developers is you often get to see tips and tricks they have learned over the years. ActionScript 3 has a lot of new features and functionality and even after working with it for more then 3 years (I started playing with it when we started development of Flex 2 @ Macromedia) I still haven’t delved into the deepest corners of the language.
I am working on a project that involves the amazing team at gSkinner and Grant was walking the teams through some existing code (I will talk more about the project in the future). One of the sections of code involved heavily nested loops and he pointed out a neat feature of the language.
When using loops you can name them using a method similar to namespaces (in fact it may leverage the same mechanism). By naming a loop when you call break you can target the named loop as the break. This is great when you have deeply nested loops and you want to exit one of the outer loops without having to put in extra logic to determine exit strategies. For example:
// my top loop outsideLoop:for(var i:uint = 0; i < 10; i++) { trace(i + ": called from outsideLoop."); //my inside loop insideLoop:for(var j:uint = 0; j < 5; j++) { trace(j + ": called from insideLoop."); if(j < 2) break outsideLoop; // stop the outside loop } }
As you can see, you name the loop by using [name]:loop structure which then allows you to reference the loop from the break. Its a nifty little trick that can help with those often complex nested loops. Enjoy!
5 Responses to “ActionScript 3.0: Named Loops”
By webnesto on Apr 12, 2008
that is fuck-off cool. I now am angry that every language doesn’t support this.
By webnesto on Apr 12, 2008
that is fuck-off cool. I now am angry that every language doesn’t support this.
By webnesto on Apr 12, 2008
that is fuck-off cool. I now am angry that every language doesn’t support this.
By James on Apr 12, 2008
Its one of those things that you wish you knew back when you needed it but luckily this is not too common of a problem. Next time it comes up then I know how to solve it.
By spudnik187 on May 7, 2008
Very nice find. This could have come in handy in several projects I’ve worked on recently.