• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Using Variables

After you stuff a particular data type into your variable’s value, there are only a few things you can do with the variable. You can access its value (just to look at it or use it within an expression), change its value (that is, assign a new value— which is really what you do when you set its initial value), compare its value with another variable or expression, or pass the value to a function for the function’s use. It might sound as though that’s a lot of maneuvers to learn, but it’s really not that bad.

Assigning and Accessing Variables

You’ve already seen how to assign values to variables many times in this chapter, but it doesn’t hurt to go over the details. The most common form is variableName=newValue. You can translate this to read “the variable named ‘variableName’ is assigned the value of newValue.” If, whenever you read the equals sign, you say to yourself, “…is now equal to…” or “…is assigned the value of…,” it should make sense. This means that no matter what the value the variable (on the left side) contains before this statement is encountered, it is now assigned the value of whatever is on the right side. If an expression such as price/2 is on the right side in the code halfPrice=price/2, the right side is evaluated first and the result is placed in the variable on the left.

You actually saw another way in which variables are assigned values—namely, with assignment operators, such as ++ (which increments the variable to the left of the operator). The confusing part is that many operators don’t actually change the contents of their operands. For example, discountPrice= (0.15*originalPrice) won’t change the value of originalPriceoriginalPrice is just being referenced so that it can be used within an expression. But a statement such as age++ will change the value of _age by increasing it by one. The most common way in which variables are assigned values is through the equals sign—just don’t forget the assignment operators (++, ––, +=, and -=).

One last point to remember when assigning values: If you want to copy the value of one variable into another (for instance, myName=username), just remember the difference between primitive and reference data types. If username contains a string (primitive), a duplicate of its contents is placed into the value of myName. However, if username contains an array (that is, a reference data type), only a reference is placed into the variable myName. After that, if username changes, so does the value in myName.

Accessing variables can be very simple. You just use the variable’s name. Variables are evaluated wherever they’re used. That is, if you say username, the value of username is used in that place. Just as 3+2 evaluates to 5, using a variable’s name evaluates to its value. This might seem very simple, because it is! The tricky part is making sure that you’re referring to the right variable name (which is covered in more detail later in this chapter).

Comparing and Passing Values

Quite often, you’ll find the need to compare or check whether a variable’s value either matches, is greater than, or is less than another variable’s value. Sometimes you compare a variable’s value to an expression, such as:

if (age>17){

In this case, we’re simply checking whether the value of age is greater than 17. (We’ll cover the if statement in detail in Chapter 5, “Programming Structures.”) Consider that, in this case, 17 is “hard wired.” What if the minimum age to vote changes? If you expect there’s a chance of changes, you could first assign the value to another variable (minimumAge) and create a slightly more dynamic solution:

if (age>minimumAge-1) {

In this case, we’re comparing the value of age to the expression “minimumAge minus 1.” You’ll do a lot of this kind of thing in any programming language, but there are two important concepts to remember. First, such comparisons never change any variable’s values. If you’re checking whether two variables happen to be equal, use the following:

if (oneVariable==otherVariable){
//then... do whatever 

The double equals sign doesn’t change oneVariable or otherVariable. In Chapter 9, you’ll also learn about Flash MX’s new strict equality comparison operator (===). (That’s three equals signs.). The regular equality operator (==) just compares two values, whereas the strict equality operator (===) also compares two variables’ data types. Again, only the regular assignment operator (=) actually changes variables. The second concept to remember is that when comparing two primitive variables, the contents of each are compared—number for number or letter for letter. (This is likely the way you expect.) However, if you’re comparing two variables that contain (references to) reference variable types, the comparison checks only whether both variables point to the same original. For example:

oneArray=["Phillip", "Kerman"]; 
anotherArray=["Phillip", "Kerman"]; 
//that line only placed a reference to "oneArray" in "oneRef" 
if (oneRef==otherRef){
//they match! 

The expression after the if statement’s condition (oneRef==otherRef) evaluates as false. Even though the actual contents of both variables look identical, they’re pointing to two different arrays (which, remember, are reference data types). The entire subject of “primitive versus reference” might seem esoteric (and I suppose it is in many ways). However, you’ll find arrays so powerful that the last thing you’ll need is to hunt down a bug that’s caused by this (less than intuitive) behavior. The two points to remember from this section so far are that comparing variables in an expression doesn’t actually change them, and that different data types behave differently.

Finally, let’s consider passing variables. When you write your own functions in Chapter 8, you’ll see that there’s an opportunity to write a function that accepts parameters. This concept is similar to how gotoAndStop() requires that you provide a parameter—namely, a frame number or label name to go to. Often you’ll write functions that will act differently depending on parameters that are received. For example, you might write a custom exchangeCurrency() function that accepts one price and determines the price in another currency (like we’ll do in Workshop Chapter 8, “Creating a Currency Exchange Calculator”). To use this (yet-to-be-created) function, you’d simply say exchangeCurrency(1.95). If you provided a different parameter (the part in the parentheses), such as exchangeCurrency(14.50),you’d get a different answer. Instead of a hard-wired number, you could pass a variable instead—for example, exchangeCurrency (currentPrice). In this case, the value for currentPrice would be passed. As long as the value of currentPrice contained a primitive data type, the original can never be changed by the function. If the currentPrice were a reference data type, you could write the function to change the original value. Only reference type variables can be changed in this way. Often you’ll pass variables of the primitive data type (see Workshop Chapter 8) and hence only pass copies of the variable. However, in Workshop Chapter 6, “Working with Odd-Shaped Clickable Areas,” you’ll actually pass references to Movie Clips (which is a reference data type—object). In that workshop, changing the parameter received will most definitely change the original Movie Clip instance. (You’ll learn much more about functions in Chapter 8.)

Scope and Variable Collision

As stated earlier, when you place a variable’s name in a script, the variable’s value is used in its place. I said it was easy as long as you used the correct variable name. Certainly, you’ll need to remember which variable is which. It’s just as if you have several children with different names; you need to keep track of which one is which. With kids, it’s pretty easy because you memorize their names. You can name your children (and your variables) anything you want. Although some people name their children with their own name, most people tend to use a unique name for each child. You can imagine the problems that would arise if you named two of your children with the same name. In Flash, you can’t exactly get away with giving two variables the same name—but almost.


Actually, you can’t really name your variables just anything. Variable names must start with a character other than an underscore (_myAge, for example, won’t work) or a number (2Cool won’t work, either). Also, you can’t include spaces in a variable name— only one word per variable, although people often use uppercase characters to make a variable seem like two words (myVariable, for example).

In traditional programming the scope of a variable (either local or global) defines the area in which that variable has influence—sort of like a sheriff’s jurisdiction is his scope. In Flash MX, there are really three types of variables: true globals, true locals, and then all the rest, which are called timeline variables. Unless you specify a variable as global or local, it falls into the timeline category. (If I don’t call a variable global or local in this book, you can count on it being a normal timeline variable.)

In actuality, timeline variables are like traditional global variables because they can be accessed from any script. It’s just that with timeline variables you must be explicit in order to avoid variable collision. Variable collision occurs when you try to have two variables with the same name, but expect them to maintain separate values. For example, it’s perfectly logical to have a variable called “president” that stores the name of the President of the United States. However, what if you want another variable called “president” that stores the name of the president of your club? Obviously, the two variables would collide if you said president="George" and then later said president="Mary". In Flash, however, you simply need to be explicit, and instead, store each variable in it’s own clip instance. Say you had two clip instances, one with an instance name “usa” and the other called “club.” You could be explicit and say usa.president="George" and club.president="Mary".

You’ll learn the details of this syntax in Chapter 7, but for now just realize that two variables in different Movie Clip instances don’t collide because their explicit location (clip address) is unique. To understand variables better, compare them to properties. Variables unique to a clip instance are the same as how the _y property of one clip instance (oneInstance._y) can be uniquely different from the _y property of another instance of the same clip (otherInstance._y). Anywhere inside a Movie Clip, referring to _y refers to the _y of that clip, just like president refers to that clip’s president. There’s only one version of _y anywhere inside the clip, but as soon as you need to write an explicit reference to one of the clip’s properties or variables, you need to precede the property or variable with the clip instance name.

Finally, I should note that keeping variables with the same name inside multiple clip instances could be very useful. Think of such timeline variables as similar to the properties unique to clip instances. For example, assume that you create a Movie Clip that uses the variable speed. You can drag multiple instances of that clip on the Stage and each instance will have its own speed, just as each instance maintains its own _alpha property, _x property, and so on. The only concern is to be clear which clip’s variable you’re referring to so that you don’t get mixed up.

Global Variables

Flash MX added true global variables. There’s only one copy of any global variable. In the case of “president,” if this were a global variable, you’d never need to wonder, “Which president?” Using global variables is easy. The name of any global variable always begins _global. For example, you could use _global.president to refer to the global variable called president. It’s like there is an imaginary clip called _global in which you can store variables. Just remember that you can have only one version of any named global variable. Global variables are really not much different from normal variables that are unique to a timeline. It’s just that every time you refer to a global variable, you should be explicit and use the _global. prefix.

Global variables make keeping track of variables easy. You never have to remember which clip they’re stored in, or whether there’s another variable with the same name. As such, they’re only appropriate for certain types of data storage. Variables are a way to store data. Global variables are appropriate for data of which there’s only one copy (_global.totalScore or _global.todaysDate, for example). However, if you built a game with two players, you couldn’t have one global variable called _global.score because you wouldn’t be able to store a value for each player. We’ll get into the practical use of all variable types later. Just remember that global variables always start “_global.” and that there’s only one copy of each.

Local Variables

Even though most of your work won’t involve local variables, they’re good to understand—if, for nothing else, comparison. Local variables are used within custom functions and exist only for the short duration while they’re used. The benefit is that local variables are always removed from the user’s computer memory when they’re not being used. Other variables take up space in RAM and will never “let go” of that memory unless you use delete (as in delete someVarName). You can also just assign a value that’s practically insignificant, such as someVarName=0, which isn’t the same thing but perhaps is easier to understand.

Local variables have to first be declared, using either of the following forms:

var counter;


var counter=0;

In the second case, not only is the local variable (counter) created, but it’s assigned a value from the start. In the first example, you’d have to eventually assign a value to the variable before it could be used. Just remember that such a variable is still useful to temporarily hold a value to be used later, but it only “lives” within the function (that is, between the { and } curly braces). You can practice with local variables when you learn all about functions in Chapter 8.

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint