I l @ ve RuBoard |
Local and Global VariablesIn Hour 3, "Learning to Program," I mentioned variables. They are little containers for storing information. Setting VariablesUsing variables in ActionScript is easy. All you need to do is assign a value to a variable name . Here is an example: myVariable = 7; The preceding line creates the variable named myVariable and places the number 7 inside it. Note that the name myVariable was chosen arbitrarily by me. You could name the variable anything. For instance, numberContainer , a , or fred would all work. To see variables in action, you can test them with the Output window. Here is a short program that you can place in the first frame of a blank movie: myVariable = 7; trace(myVariable); When you run this movie, the Output window appears with the number 7 in it. The number 7 was stored in myVariable and then the trace command was used to place the contents of myVariable in the Output window. Global Variables
You don't need to do anything special to create a global variable. Just using it, like in the previous example, automatically makes the variable a global one. In most programming languages, global variables are available everywhere. However, Flash movies use a system of levels. The main movie timeline is the root level. Any movie clips are actually small Flash movies inside the main one. The graphics and scripts inside a movie clip are one level down from the root level. Global variables at the root level aren't accessible inside a movie clip ”at least not directly. Local Variables
The point of local variables is to create modular code. If a variable is local, it is removed from memory when the script is finished. Otherwise, if it is a global variable, the variable and its value will hang around until the movie ends. To create a local variable, you need to use the var keyword. For instance, you could create a local variable named myLocal and place the number 9 in it like this: var myLocal = 9; After you set the variable with the var keyword, you don't have to use var again in that local piece of code. For instance, the following code creates the local variable, sets it to 9, changes its value to 11, and then sends it to the Output window: var myLocal = 9; myLocal = 11; trace(myLocal); When deciding when to use local variables and when to use global variables, the rule of thumb is to always use local variables unless there is a good reason to use a global. We'll mostly use local variables. |
I l @ ve RuBoard |