FITC Hollywood discount →← AIR Bus

AS3: Label Statements

I’ve read about this in a couple of places and never had much of a use for it until now. But it’s really relevant and (as Josh would say) real slick.

Label statements allow you to keep track of different loops or switch statements (or anything that can break or continue, for that matter). By referencing a loop with a label statement, you can specifically force ActionScript to exit that loop.


Consider this:


for(var i:int=0;i<100;i++)
{
for(var ii=0;ii<100;ii++)
{
if(ii == 5) // I want to break right here.
}
}

There are lots of ways to skin this cat, but this strikes me as the easiest (and most readable):


outerLoop: for(var i:int=0;i<100;i++)
{
innerLoop: for(var ii:int=0;ii<100;ii++)
{
if(ii == 5) break outerLoop; // done.
}
}

By calling break on the outerLoop, I automatically exit both simultaneously. And my coder colleagues will thank me for specifying what is happening here. Especially if I have a loop within a loop within a switch within a loop.

Read all about it on the livedocs.

September 27th, 2007  by Stephen  /  6 Comments

Comments on “AS3: Label Statements”

  1. […] jordan@list.ru (Sergey Lepilov) wrote an interesting post today!.Here’s a quick excerptLabel statements allow you to keep… Labs is the Big Spaceship dev team’s playground, where we share ideas and discuss code. Check out labs.bigspaceship.com for more discussion, as well as some of the tools we’ve built! […]

    GadgetGadget.info - Gadgets on the web » AS3: Label Statements on September 27th, 2007 at 12:08 pm
  2. Nice!
    Never heard of that option… Thanks for sharing!

    Quentin on September 27th, 2007 at 12:40 pm
  3. Real Slick.
    5uflash.com is the livedocs? ;)

    Matt on September 27th, 2007 at 1:01 pm
  4. Exellent trick!

    Özgür ALTAY on September 28th, 2007 at 6:33 am
  5. Oh! Oops. I’ll update that. :)

    I have 7 different links that explain it. The livedocs is the clearest. Sorry!

    Jamie on September 28th, 2007 at 8:11 am
  6. I know this is an old post, but I’m having trouble getting this to work with a continue statement:
    outerLoop: for(var i in a){
    trace(i);
    for(var j in a[i]){
    trace(’ ‘+j);
    continue outerLoop;
    }
    }

    This gives me an error: 1039: Target of continue statement was not found.

    It works if I use break outerLoop (but it doesn’t do what I want). Seems simple as day but it doesn’t work as described in the livedocs at all!

    Aaron Beall on July 14th, 2008 at 3:36 pm