Posted by: Actionscription | June 20, 2008

Down Variable Scope

Duplicate variable definitions error

So, have you written a couple perfect loops in AS3 only to generate the compiling error “duplicate variable definitions“? I just did that and the error is a little misleading.

So here’s a little background. In AS3, you are not allowed to define a variable and then redefine it later, like this:

var i:Number = 314159;
var i:String = "314159"

.
Once you define a variable, you’re stuck with it. If you do something like the above code, you receive the “duplicate variable definitions” error.

Here’s the weirdness: you receive that same error when you declare a variable more than once in the same scope. This should have a different error name like, “duplicate variable declarations,” but Adobe wasn’t that creative. Oh well.

So here’s an example of what not to do, unless you desire a “d.v.d.” error message :O)

var i:Number = 314159;
var i:Number = 22222;

.
It should look like this:

var i:Number = 314159;
i = 22222;

.
This carries over to for statements (aka loop statements) that are in the same scope. The following code will produce a d.v.d. error:

for(var i:Number = 0; i < array.length; i++){
    //code here
} 

for(var i:Number = 0; i < array.length; i++){
    //other code here
}

.
Avoid the error by changing the var’s name in the second loop:

for(var i:Number = 0; i < array.length; i++){
    //code here
} 

for(var j:Number = 0; j < array.length; j++){
    //other code here
}

.
Another solution is to declare the var outside of both statements:

var i:Number = 0
for(i = 0; i < array.length; i++){
    //code here
} 

for(i = 0; i < array.length; i++){
    //other code here
}

.
All set! No more d.v.d. errors!

Curtis Morley explains it well unfortunately in the last comment in the following link: CurtisMorley on Variable Scopes.


Responses

  1. Thanks for visitng http://www.curtismorley.com. I have changed the code examples in my post to match those in the comments area for AS3 Error 3596.

    Thanks again,

    Curtis J. Morley


Leave a response

Your response:

Categories