Skip Navigation.

Flash Programming: Variables

Variables are information holders. Think of them as boxes with labels. The labels are the variables' names and the contents are the variables' values. Below are a few details about variables and how to use them.

Names
Variable names can be whatever you like them to be, with a few caviats. First, they must be one word. Second, they must be unique within their scope. Finally, they cannot be the same as any boolean values (you may not have a variable named true, for instance).

Sometimes, it helps to have a naming scheme for your variables. Say, for instance, that you always begin your variables with a capital letter and follow them with only lower case letters. This can help you distinguish variable names later on.

Scope
A variable's scope is the area in which it is recognized. There are two scopes for variables in Flash: global and local. Global variables retain their value throughout a program; they are a useful way to keep track of data needed throughout your movie. Local variables are only defined for a particular function or for the block of code (loop) in which they are declared. This means that when the function is done running, they are erased and forgotten.

Declaring variables
Global variables can be declared at any time. You can either use Flash's "set Variable" action or you can include a line of code using the " = " operator. An example of such code is below:
Score = 6000;

Local variables can be declared within any function or block of code by using the "var" function. Such variables will be erased after the block of code or script is finished running. An example of a local variable declaration is below:

var DogsLeftToPet = 10;

Types of data
A variable may hold two different types of data. Depending on the type of data its been assigned, it will act differently.

Numbers are numerical values that Flash can use in mathematical expressions and equations. When a variable has been assigned a numerical value, it can be manipulated just as if it were that value. See our example below.

DogsLeftToPet = 10;
DogsPettedToday = 3;
DogsLeftToPet = DogsLeftToPet - DogsPettedToday;
DogsLeftToPet => 7

Strings are groups of characters. Flash doesn't really understand what they mean, but it can shuffle them around and compare them. To assign a string value to a variable, use quotation marks around your data. See the example below.

FavoriteIceCream = "Rocky Road";

NOTE: You can have a variable that holds a string of numbers. The Number and String functions in the ActionScript Library help you change data from a string to a number and back.

Learning to use variables is an important step in learning to program effectively. Be sure to read the above information carefully before moving on.

Back