About variables 97
Global variables
Global variables and functions are visible to every timeline and scope in your document. To
declare (or create) a variable with global scope, use the
_global identifier before the variable
name and do not use the
var = syntax. For example, the following code creates the global
variable
myName:
var _global.myName = "George"; // Incorrect syntax for global variable
_global.myName = "George"; // Correct syntax for global variable
However, if you initialize a local variable with the same name as a global variable, you don’t
have access to the global variable while you are in the scope of the local variable, as shown in
the following example:
_global.counter = 100; // Declares global variable
trace(counter); // Accesses the global variable and displays 100
function count():Void {
for (var counter:Number = 0; counter <= 2; counter++) { // Local variable
trace(counter); // Accesses local variable and displays 0 through 2
}
}
count();
trace(counter); // Accesses global variable and displays 100
This example simply shows that the global variable is not accessed in the scope of the count()
function. However, you could access the global-scoped variable if you prefix it with
_global.
For example, you could access it if you prefix the counter with
_global as shown in the
following code:
trace(_global.counter);
You cannot assign strict data types to variables that you create in the _global scope, because
you have to use the var keyword when you assign a data type. For example, you couldn't do:
_global.foo:String = "foo"; //syntax error
var _global.foo:String = "foo"; //syntax error
The Flash Player version 7 and later security sandbox enforces restrictions when accessing
global variables from SWF files loaded from separate security domains. For more information,
see Chapter 17, “Understanding Security,” on page 677.
Timeline variables
Timeline variables are available to any script on that particular timeline. To declare timeline
variables, use the
var statement and initialize them in any frame in the timeline. The variable
is available to that frame and all following frames, as shown in the following example.