Local variables and scope in AS3

  1. if(wadus){
  2.    var x:int = 8;
  3. } else {
  4.    trace(x); // <– 0
  5. }

Yep, that’s right. You can trace x in the else branch and you get 0 (I’d expect an error at compile time). This is obviously a simplified case but something like this just happened to me by mistake and took me a while to realize.

Another example:

  1. function wadus(e:Event):void{
  2.  
  3.    try{
  4.       // something
  5.    } catch(e:*){
  6.       trace(e); // <- That’s the exception, not the parameter!
  7.    }
  8.  
  9. }

I’m sure MTASC didn’t allow such things, and I miss it (snif, snif). You can read AS3 vs Java Local Variable Scope for more info:

[...] the AS3 compiler takes all the local variables (regardless of depth) and declares that right at the beginning of the function [...] This behavior is similar to the way Flash deals with variables declared later on the timeline, you can reference them before earlier than the declaration because the compiler moves that declaration to the beginning

Yes, it sort of makes sense from a Flash point of view, but I don’t like it ¬¬

One Response to “Local variables and scope in AS3”

  1. Brett Says:

    Hi I have a problem that I am wondering if you could help with. is it possible to check or even change a variable declared on the timeline in a movie clip from outside that clip in AS3.

    i.e. changing a var declared on the timeline of a child Movie clip.

    trace(my_mc.myTimelineVariable) //null

Leave a Reply