Monday, July 14, 2008

Scope of Actionscript 3.0 Variables

Did you know that in Actionscript 3.0, there is no block scope for a variable? The minimal scope is the function, meaning that the declaration of a variable in an "if" statement for instance, can be reused in the "else" statement. Incredible for an old C++ developer like me!!! A small example to illustrate my thoughts:


public function helloWorld() : void
{
   var a:int = 0;
   if ( a )
   {

      var u:int = 5;
   }

   else
   {
      u = 6;
   }

   trace( "u -> " + u );
}



Guess what? No compilation error, and u = 6! Careful though if you declare an Object! The variable exists, but if it's initialized in the "if" statement, it will equal "null" if you pass in the "else" block!

An interesting link on differences between Java 5 and Actionscript 3.0.

3 comments:

Jeremy said...

While this may be true, it is confusing for one developer to look at another developer's code employing this style, making debugging much more difficult. I would recommend staying away from this practice if at all possible.

Barbara said...

Yeah, you're completely right. Could lead to nasty bugs to investigate :-) I guess the ideal would be for the next generation of AS to introduce block scopes so that if you declare a variable in one block, you can declare another one of the same name in another block of the same function without getting the warnings (that's how I discovered this "feature" in the first place).

Darren said...

Looked at another way - maybe no block scope is a good thing? It encourages developers to use unique, relevant variable names. Apart from the annoying warning, the only time I can see it causing a real problem is if a variable is re-used without initialising it first.

I do like using 'i' and 'j' for counters but if you keep your functions small by breaking them up into smaller functions, even this won't be an issue. When I think about it, it's probably good practice to never re-use the same variable name in the same function anyway.