Saturday, July 19, 2008

AS3 vs Java Local Variable Scope

In some languages, you can scope variables within blocks of code, like in different compound statements. For example, the following is legal in Java:
int i = 0;
int i = 1; //Legal in Java
But adding those {} to make a compound statement does NOT work in
ActionScript 3 because the AS3 compiler takes all the local variables
(regardless of depth) and declares that right at the beginning of the
function. For example, this is legal in AS3:
    trace(i); // Legal in AS3, default value of int (zero) is output
var i:int = 1;
It appears we're accessing a variable before it is declared. But since the compiler moved our declaration to the beginning of the function, there is no error. The assignment is not moved, the the value of i at that point is zero. This behavior is similar to the way Flash deals with variables
declared later on the timeline, you can reference them before earlier
than the declaration because the compiler moves that declaration to
the beginning.