Variable Clashes
Scoping is pretty weird in AS3 for those coming from C/C++ and Java. There are two cases in particular you should know about.
The first you’ll probably see pretty quickly upon starting your AS3 programming:
function printTwice(a:Array): void { for each (var cur:String in a) { trace(cur); } for each (var cur:String in a) { trace(cur); } }
You get this compiler warning twice:
Warning: Duplicate variable definition. for each (var cur:String in a) ^
This betrays what’s going on behind the scenes: there is no loop scope! All local variables are scoped to the function. So there’s a clash here, but it’s OK because the compiler will just pretend that you didn’t declare the second one and instead just re-use the first. This is dangerous, hence the compiler warning.
Recently though, I discovered this evil little variable clash:
function printLength(a:Array): void { var a:Array; trace(a.length); }
Firstly, there are no compiler errors or warnings this time around. There should be. Secondly, say I call printLength([2,4,6])
. What do you figure gets printed? The answer is nothing. The a
declared in the function overrides the a
declared in the arguments list. There is, in fact, no way to reference the argument by its name (a
), only by arguments[0]
. So the trace
statement is accessing a null reference and you will get a crash. Just like I did. I hope, having read this article, you will be extra vigilant with this. And if you’re not, I at least hope you can debug it faster.
#1 by skyboy on October 23rd, 2010 ·
I don’t fully understand your first example/warning pair.
As for the second one, that’s allowed because of the
arguments
variable, allowing you to access the argumenta
witharguments[0]
.#2 by jackson on October 24th, 2010 ·
Thanks for catching these! I’ve updated the article so the first example has the proper warning. It’s been quite a while since I wrote this article, but I have no idea how I got the warning that was there. I’ve also updated the second example to include
arguments[0]
, as you suggest, since it is definitely a way to access the parameter. It’s still a shame that the compiler behaves this way: it’s absurd that there is no error or even warning and the generated program behavior is quite unexpected, at least to me.#3 by skyboy on October 24th, 2010 ·
There’s another article a few further along (newer) where you copy/pasted the wrong code from someone’s comment as well, but I don’t recall which one; And I agree, this is most definitely a bug (as in another article you showed different types throw a warning/error), and should be reported.