User Guide
Variables 51
Variables
Variables allow you to store values that you use in your program. To declare a variable, you
must use the
var statement with the variable name. In ActionScript 2.0, use of the var
statement is only required if you use type annotations. In ActionScript 3.0, use of the
var
statement is always required. For example, the following line of ActionScript declares a
variable named
i:
var i;
If you omit the var statement when declaring a variable, you will get a compiler error in strict
mode and run-time error in standard mode. For example, the following line of code will result
in an error if the variable
i has not been previously defined:
i; // error if i was not previously defined
To associate a variable with a data type, you must do so when you declare the variable.
Declaring a variable without designating the variable’s type is legal, but will generate a
compiler warning in strict mode. You designate a variable’s type by appending the variable
name with a colon (:), followed by the variable’s type. For example, the following code
declares a variable
i that is of type int:
var i:int;
You can assign a value to a variable using the assignment operator (=). For example, the
following code declares a variable
i and assigns the value 20 to it:
var i:int;
i = 20;
You may find it more convenient to assign a value to a variable at the same time that you
declare the variable, as in the following example:
var i:int = 20;
The technique of assigning a value to a variable at the time it is declared is commonly used
not only when assigning primitive values such as integers and strings, but also when creating
an array or instantiating an instance of a class. The following example shows an array that is
declared and assigned a value using one line of code.
var numArray:Array = ["zero", "one", "two"];
You can create an instance of a class by using the new operator. The following example creates
an instance of a named
CustomClass, and assigns a reference to the newly created class
instance to the variable named
customItem:
var customItem:CustomClass = new CustomClass();