Lack of Block Scoping in AS3 - Beware
August 4th, 2008I’ve known about AS3’s lack of block-scoping since I first got those weird duplicate variable definition warnings. We’ve all seen them many times, especially when we take a vacation to the land of C++ or Java. What do you mean duplicate variable? I declared that in an IF statement or a different loop? Well for the first time it actually caused me some grief today rather than just annoyance, albeit briefly.
I declared a String inside a FOR loop, knowing that in AS3 object references are initialized to null. I wrote logic around this fact, thinking I knew what was going on and trying to be slightly more efficient by not initializing to empty String if I don’t need it, etc. It went something like this:
var i:int;
var n:int = 20;
for(i=0;i
var str:String;
if(…something)
{
str = “return from some function”;
}
if(str)
{
//some more logic here;
}
}
So what’s wrong with this? Well I wrote it with the only thought in my head being that AS3 initializes String’s to null, so each pass through the loop, str would be initialized to null, it could possibly be set to some non-null String, I’ll check for that and execute some code or move on. Unfortunately I overlooked the fact that AS3 does NOT support block scoping, which basically means all variable declarations are pulled out to the top of their containing function; therefore, str would be initialized to null when entering the function, but would not be re-initialized to null on each iteration of the loop. After each iteration str retained it’s previous value, which defeated the logic that loop was based on.
Easy fix? Yeah! Initialize str to null. Or just rewrite the logic, but this was way easier.
var str:String = null;
This looks a bit redundant when reading the code as it makes it seem like I’m intializing to the default value, but due to the fact that the declaration does not actually happen inside the loop, I’m simply resetting str to null on each pass.
I’m highly considering pulling all of my variable declarations out to the top of the function definition when working in AS3. This does not fit into my normal coding conventions, but it’s more in line with what is actually happening in compiled code, and may serve as a reminder to avoid future pitfalls. It’d also get rid of those pesky duplicate variable definitions…