User Guide

46 Chapter 2: ActionScript Basics
Make sure to declare a Timeline variable before trying to access it in a script. For example, if you
put the code
var x = 10; in Frame 20, a script attached to any frame before Frame 20 cannot
access that variable.
Local variables
To declare local variables, use the
var statement inside the body of a function. A local variable
declared within a function block is defined within the scope of the function block and expires at
the end of the function block.
For example, the variables
i and j are often used as loop counters. In the following example, i is
used as a local variable; it exists only inside the function
initArray():
var myArray:Array = [ ];
function initArray(arrayLength:Number) {
var i:Number;
for( i = 0; i < arrayLength; i++ ) {
myArray[i] = i + 1;
}
}
Local variables can also help prevent name conflicts, which can cause errors in your application.
For example, if you use
age as a local variable, you could use it to store a persons age in one
context and the age of a persons child in another; because these variables would run in separate
scopes, there would be no conflict.
Its good practice to use local variables in the body of a function so that the function can act as an
independent piece of code. A local variable is changeable only within its own block of code. If an
expression in a function uses a global variable, something outside the function can change its
value, which would change the function.
You can assign a data type to a local variable when you define it, which helps prevent you from
assigning the wrong type of data to an existing variable. For more information, see “Strict data
typing” on page 41.
Global variables
Global variables and functions are visible to every Timeline and scope in your document. To
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 dont 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(){
for( var counter = 0; counter <= 2 ; counter++ ) { //local variable
trace(counter); // accesses local variable and displays 0 through 2