User Guide

Variables 53
If the variable name you use for your local variable is already declared as a global variable, the
local definition hides (or shadows) the global definition while the local variable is in scope.
The global variable will still exist outside of the function. For example, the following code
creates a global string variable named
str1, and then creates a local variable of the same name
inside the
scopeTest() function. The trace statement inside the function outputs the local
value of the variable, but the
trace statement outside the function outputs the global value of
the variable.
var str1:String = "Global";
function scopeTest ()
{
var str1:String = "Local";
trace(str1); // Local
}
scopeTest();
trace(str1); // Global
ActionScript variables, unlike variables in C++ and Java, do not have block-level scope. A
block of code is any group of statements between an opening curly brace (
{ ) and a closing
curly brace (
} ). In some programming languages, such as C++ and Java, variables declared
inside a block of code are not available outside that block of code. This restriction of scope is
called block-level scope, and does not exist in ActionScript. If you declare a variable inside a
block of code, that variable will be available not only in that block of code, but also in any
other parts of the function to which the code block belongs. For example, the following
function contains variables that are defined in various block scopes. All the variables are
available throughout the function.
function blockTest (testArray:Array)
{
var numElements:int = testArray.length;
if (numElements > 0)
{
var elemStr:String = "Element #";
for (var i:int = 0; i < numElements; i++)
{
var valueStr:String = i + ": " + testArray[i];
trace(elemStr + valueStr);
}
trace(elemStr, valueStr, i); // all still defined
}
trace(elemStr, valueStr, i); // all defined if numElements > 0
}
blockTest(["Earth", "Moon", "Sun"]);