Local variables and scope in AS3

[code lang="ActionScript"]if(wadus){
var x:int = 8;
} else {
trace(x); // <-- 0
}[/code]

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:

[code lang="ActionScript"]function wadus(e:Event):void{

try{
// something
} catch(e:*){
trace(e); // <- That's the exception, not the parameter!
}

}[/code]

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 ¬¬

Back to index