I hadn’t faced a situation like this one in the previous builds of Flex 2.0, but I’m working with some new code. For some reason, I’m getting errors when I use the same variable name but different types for variables that are in different scopes. It’s a pain because its the “i” variable in a for
loop. This issue seems to happen only within a single function.
private function scopingIssue():void { if(this.width == 100) { for(var i:Number = 0; iBoth those
for
loops are in different scopes, so they should work as different types, but I get the error, "A conflict exists with definition i in namespace internal". This is definitely a bug. Can someone remind me where to find the bug submission form?
MTASC would bitch for the same reason in AS2. Basically, can’t re-declare the variable of the same name again, let alone to a different datatype. Although you and I see it as a different scope, the compiler see’s it as a function block with 2 local variables defined twice, which can you’d do.
Submit the bug at the appropriate forum at labs.adobe.com.
I made a similar function in MTASC, except I declared i as a String the second time. No errors. The if and else blocks should be different scopes, or at least that’s how other languages work.
Actually, it’s not a bug. ECMAScript3 (Javascript, AS1) doesn’t support block level scoping, and ECMAScript4 (AS3) needs to be backwards compatible with it. So AS3 doesn’t have block level scoping. Which means that all variables declared inside a function are visible anywhere in the function. So you can’t declare the same variable twice with different types.
Thanks Ely, good to know.
I’m used to the idea of any {} block making a new scope. I know of some developers that will force a limited scope in other languages by just building an artificial block around a section of code. I suppose it would be a good way to force a garbage collection in C# or Java.
It totally sucks! A closing brace should always be the end of a scope, period.
The ECMAScript 4 specification defines a
let
keyword that may be used instead ofvar
. This new keyword will allow you to keep scope inside a block rather than at the function level. Stayed tuned for it in a future update to ActionScript!