About variables 99
If the variable name you use for your local variable is already declared as a timeline variable,
the local definition takes precedence over the timeline definition while the local variable is in
scope. The timeline variable will still exist outside of the function. For example, the following
code creates a timeline string variable named
str1, and then creates a local variable of the
same name inside the
scopeTest() function. The trace statement inside the function
generates the local definition of the variable, but the
trace statement outside the function
generates the timeline definition of the variable.
var str1:String = "Timeline";
function scopeTest():Void {
var str1:String = "Local";
trace(str1); // Local
}
scopeTest();
trace(str1); // Timeline
In the next example, you can see how certain variables live only for the life of a specific
function and can generate errors if you try to refer to the variable outside the scope of
that function.
To use local variables in an application:
1. Create a new Flash document.
2. Open the Actions panel (Window > Actions) and add the following ActionScript to Frame
1 of the Timeline:
function sayHello(nameStr:String):Void {
var greetingStr:String = "Hello, " + nameStr;
trace(greetingStr);
}
sayHello("world"); // Hello, world
trace(nameStr); // undefined
trace(greetingStr); // undefined
3.
Select Control > Test Movie to test the document.
Flash displays the string “Hello, world” in the Output panel and displays undefined for
the values of
nameStr and greetingStr because the variables are no longer available in
the current scope. You can only reference
nameStr and greetingStr in the execution of
the
sayHello function. When the function exits, the variables cease to exist.