Skip to main content
Inspiring
April 28, 2013
Question

declare variables in for-statement

  • April 28, 2013
  • 1 reply
  • 987 views

This works and traces '2' five times:

for (var i = 0; i < 5; i++)

{

var d:int = 2;

trace(d);

}

I sort of understand why this doesn't:

var d:int = 2;

trace(d);

var d:int = 2;

trace(d);

var d:int = 2;

trace(d);

var d:int = 2;

trace(d);

var d:int = 2;

trace(d);

Since I get the next error:

1151: A conflict exists with definition d in namespace internal

cause I declare the same variable five times.

The thing I don't understand is why it does work in the for-loop, since in principle I'm doing the same thing there. Why isn't it a problem for actionscript when I let the same variable be declared over and over again when I use a for-loop?

This topic has been closed for replies.

1 reply

Inspiring
April 28, 2013

One way to look at it is that you declare variables for compiler - not runtime. Thus - from the compiler perspective even if you declare var in a loop - it is a single declaration statement.

jiggy1965Author
Inspiring
April 28, 2013

Don't fully understand.

for (var i = 0; i < 5; i++)

{

          trace(d);

          var d:int = 2;

}

First time the for-loop runs 'd' outputs/equals zero. Then it is declared as being 2. The second time in the loop it outputs 'd' as being 2. Then it is declared again as a variable. But Flash already knows of 'd' now and that it's 2. So shouldn't Flash give the namespace error? Just as if I were to run the 'var d:int = 2' line twice?

Inspiring
April 28, 2013

Compiler catalogues (stores in its internal "database") variables in scopes before runtime. Thus, the d declared in the loop is actually catalogued and declared BEFORE loop execution in the scope of the class that handles timeline which is internal by default. Compiler tolerates duplicate variable declarations in other than class scopes and just gives warning. In other than class scopes compiler declares variable just once for you and overrides duplicates.

In other words - compiler knows already about var d before first trace shows up. Since the variable is int - its default value is 0 - what you see in the trace. If d is Number - first trace will be NaN, if any other datatype - it will be null.

The fact that class scopes do not allow for duplicate variable declarations probably stems from the same root as the fact that there is no overloading in AS3 unlike in other languages.

Another illustration:

var d:Number = 100;

testMe();

function testMe():void

{

          for (var i:int = 0; i < 2; i++)

          {

                    trace(d);

                    var d:String = "s";

          }

}

In this case first trace is null although one might expect 100. This is because in the function d is property of function testMe() - not class scope (or namespace).