• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Chapter 4. Basic Programming in Flash > Data Types and Variables

Data Types and Variables

It’s difficult if not impossible to discuss either data types or variables without mentioning the other. We’ll discuss both here.

Variables’ Names and Values

Variables are a way that you can safely—yet temporarily—store data. Think of variables as individual whiteboards. You can write someone’s telephone number on one whiteboard and refer to it later. You can easily change the telephone number on the whiteboard. Variables are similar in that you can store information in a variable for later reference or change it any time. You can have as many variables as you choose. To return to our whiteboard analogy, you could have one for telephone number and one for address. Every variable has two parts: a name (so that you can keep track of which variable is which) and a value (what is stored in the variable). For example, the name of the telephone number whiteboard (or variable) could be “phonenumber,” but the value might be “800-555-1212.” To assign the value of phonenumber, you could write the script phonenumber="800-555-1212" (which, translated, reads “the variable named phonenumber is assigned the value “800-555-1212”). We’ll discuss variables at length later in this chapter, but you really just need to understand the concepts of value and name first.

String and Number Data Types

The type of data that is stored in a variable’s value is important. The type of data that goes into a variable can be one of many types. Just as you can store paper in an envelope, you can also store paper clips, money, even sand. This concept is easiest to understand when you compare two common data types: string and number.

A string is always expressed between quotation marks. “Phillip,”“David,” and “Kerman,” for example, are all strings. (Remember that we’re talking about the values contained in a variable, not the variable’s name.) You can do interesting maneuvers with strings, such as converting them to all uppercase letters and determining the number of letters in a string (using the techniques you’ll learn in Chapter 9).

Numbers (such as 13 and 35) are a different data type. Numbers are as difficult to compare to strings as apples are to oranges. You can also do interesting things with numbers, such as add them together and find their difference. However, you wouldn’t mix them. “Phillip” plus 35, for example, doesn’t make sense.

The good news about ActionScript is that it’s untyped—meaning that you don’t have to decide ahead of time the data type for each variable’s value. From context, Flash figures it out. If you said username="Phillip", Flash would treat the value of username like a string because “Phillip” is contained within quotation marks. If you said age=35, Flash would treat age as a number. (No, Flash doesn’t know what a username or age is; it just figures out the data type from how you’ve used the word.) Because ActionScript is untyped, you can change the data type in a variable. Maybe in the first frame you said score="untested" (at which point the value in the score variable would be a string: "untested"). Later, you could say score=85 (and the value of score would become a number). Despite the freedom to change data types, it’s still important to understand each data type.

More About Strings

In Chapter 9, you’ll learn all about manipulating strings. There are two tricks you should understand now, however. Concatenating two strings is just a matter of using the concatenate character +. For example, "Phillip"+"Kerman" would evaluate as "PhillipKerman". A more practical situation might be that you have an input text field onscreen (with the variable name “username”), and after the user types her name, you could use the script message="Welcome " + username + "!" and make sure to display a dynamic field containing the variable message. Notice the variable message is having its value set to a string that combines the word “Welcome “ (with an extra space) plus the value of username plus an exclamation point. Figure 4.7 shows part of such a “Hello World” exercise.

Figure 4.7. Dynamic text (based on user input) can appear by modifying strings.

Another interesting trick to understand is how to include characters that would otherwise be difficult or impossible to include inside a string. For example, what if you want your string to contain a double quotation mark, such as "Phillip is "old""? Forgetting for a moment the way you learned to nest quotation marks (inside apostrophes), the difficulty here is that the quotation mark right before the letter “o” would act like an end-quote for the quotation mark at the beginning. Instead of letting Flash get confused, you can use a backslash in front of any quotation mark you want to be used verbatim. So, "Phillip is \"old\"" works fine. This is called an escape sequence. You’ll find a table of escape sequences in Flash MX’s online help under “Understanding the ActionScript Language, About Data Types, String.” For example, \r creates a return, and \t makes a tab.

More About Numbers

Manipulating numbers will probably look familiar to you because it works the same as traditional math. Something simple like 10-2 evaluates to 8. It might seem strange that 10+2 evaluates to 12 because we just learned the plus sign (+) is the concatenation character for strings. The plus sign acts as an addition operator only when both operands are numbers. But, something odd like "Phillip"+2 evaluates to “Phillip2”, because one of the operands is a string, so the plus sign concatenates the two. Often, depending on context, Flash will use the same symbols differently.

Other number operators are pretty easy to figure out. Common arithmetic operators such as / (divide) and * (multiply) are all listed in the Operators section in the Actions panel. Remember that an expression by itself won’t do anything. For example, 2+2 evaluates to 4—but so what? If, however, you wrote myAge=2+2, the variable myAge would be assigned the value 4. You can also use variables within expressions, as in this example: myAge=myAge+1. The right side is evaluated first, and the result is placed in the value of myAge. That is, myAge is incremented (one more than it is currently).

It is good to know a few powerful shorthand operators for numbers. They’re not called “shorthand,” but rather they are categorized as “assignment operators” (and listed that way in the Actions panel) because they perform complex tasks, including assignments. One operator (the double plus sign, ++) is used to increment a variable. For example, myAge++ increases myAge by one. To decrement, use, -- (for instance, myAge--). Consider that you can write both these statements in “long hand,” as follows:

myAge=myAge+1  //performs the same thing as myAge++ 
myge=myAge-1  //same as myAe--

Finally, if you want to increase or decrease a variable’s value by more than one, you can use += or -=. For example, myAge+=5 adds five to the current value of myAge, whereas myAge-=5 subtracts five.

By the way, "3" and 3 are different; one’s a string and the other is a number. Consider the following example:


The variable myAge would become the string "31" (because the plus sign concatenated the string). This situation would easily happen if myAge were a variable associated with an Input Text field. The contents of Dynamic Text and Input Text are always treated as strings. Without fully exploring functions, I will introduce one that enables you to convert any variable into a number. It’s pretty simple: Number(myAge) will result in a number version of myAge (or whatever you put in the parentheses). So, to be sure that you have a number, you could use the assignment statement myAge=Number(myAge)+1. This example should really demonstrate how data types make a difference. (In Chapter 10, you’ll learn that associating a variable with a Text Field is not even necessary and often undesirable.)

Other Data Types

There are only a few other data types to learn. Boolean is one that’s fairly easy. The values in Boolean variables are either true or false. Perhaps you start your movie with passedTest=false, and then after the user finishes the test, you write the script passedTest=true. There are slight efficiency benefits to Booleans. You only need to consider them, however, when appropriate. Examples where Booleans make sense include PassedTest, seenIntro, and SoundOn.

Primitive Data Types Versus Reference Data Types

The data types discussed so far (string, number, and Boolean) are all considered primitive data types(sometimes called value variables). The other data types that you’re about to see (array and object) are called reference data types. Understanding the difference between primitive and reference data types is good for more than impressing people at parties.

A variable in a primitive data type (say a string username=":Phillip") copies the actual value into the variable. A variable of the reference data type only holds a pointer to the actual data. It’s sort of like the way a shortcut on Windows (or an alias on Macintosh) works—it doesn’t contain the actual data; it contains only a reference to the real thing. The difference becomes important when you begin to copy the contents of one variable into another. If the data type is primitive, copying will duplicate the contents of the variable at the time of copying. If you change the original variable’s contents, the new variable remains unchanged. In the case of a reference type, if you copy a variable and then change the original, the copy also changes. Look at the following example of copying by value (that is, using primitive data types):

myPaint="brown";      //myPaint contains "brown" 
myHouseColor=myPaint; //myHouseColor contains "brown" 
myPaint="blue";       //now myPaint contains "blue" 
                      //but myHouseColor is unchanged (it's still "brown")

Now, consider this example of copying by reference:

myFavoriteFoods=["Pizza", "Hot dogs", "Waffles"]; 
/*childhoodFoods now contains a reference to myFavoriteFoods 
(which currently contains "Pizza"...etc.) 
myFavoriteFoods=["Tiramisu", "Bitter Chocolate", "Falafel"]; 
Not only does this mean that myFavoriteFoods has changed, but since a reference to myFavoriteFoods is contained in childhoodFoods (not a copy but a reference) childhoodFoods now contains "Tiramisu" etc.—and will change any time myFavoriteFoods changes again. 


There are other subtle differences between primitive and reference data types, but if you simply understand how “copying by value” (primitive) and “copying by reference” (reference) works, you will understand the important difference.

Objects and Arrays

You might have noticed in the preceding examples of primitive and reference data types that the myFavoriteFoods variable was given a value containing more than one item (pizza, hot dogs, and waffles). That’s another data type called an array. An array simply contains several items. If you think of most variables as an empty whiteboard onto which you can write a value, an array is like a whiteboard with permanent horizontal lines separating many pieces of information. The cool part is that you can selectively find out what’s in each spot, add items, sort all the items, shuffle them, and so on. Usually, the different items are accessed by their index (that is, the position in the array). You’ll discover all the ins-and-outs of arrays in Chapter 11, but there are a couple points we can cover now so that you become familiar with what arrays look like.

You can create an array with a statement as simple as myFirstArray= ["Phillip", "Kerman", 36]. In this case, you’re creating the array and populating it all in one move. Notice that the creation process involves surrounding the data with brackets and separating each item with a comma. Also, notice that any data type can go into any index; the example has two strings and one number. (You’ll see in Chapter 11 that you can even put arrays into arrays to create a matrix.) Finally, if you’re not sure what items you plan to put in the array, but you want to create an empty array that can be populated later, you simply use new Array(), as in myFirstArray=new Array().

There’s a simple technique to manipulate arrays. You might want to access certain items in an array (by index), change the value in a particular index, or simply insert a value in a specific index. The form is arrayName[index]. But watch out: Arrays’ indexes start counting with zero. The first item is 0, and then 1, and so on. So, to write an expression that returns the third item in myFirstArray, you can write myFirstArray[2]. (Remember that because this is just an expression, it evaluates as 36 in this case; by itself, however, it doesn’t really do anything.) To change the third item, you could say myFirstArray[2]="age". Finally, you can insert an item in the 99th index position by saying myFirstArray[98]="way out". This will create at least 98 blank positions, if necessary.

Now, just to leave you with a tiny applied script, here’s a case in which I’m going to increment the value in the third index. I have to first access the item in the third position (to increment it) and set the value in the third position.

//also could have used: myFirstArray[2]++;

The last data type is object. And because Flash has many built-in objects (including Array, Math, Sound, etc.), we should call this type of object a “generic object” (also called a “homemade” or “short” object). Generic objects are similar to arrays in that you can store more than one piece of data in a single object. Whereas arrays use indexes to contain multiple numbered items, an object contains multiple named items (called properties). In addition, you can design these objects to use methods. The big difference between objects and arrays is that when you put data in an array, there’s just one copy of that array. If you change the contents in an index, it changes in the one copy. After you construct an object and the properties and methods it will contain, you can make as many duplicates as you want. Even though each instance of an object is based on the same design, each instance can maintain different values for each property.

Remember that Movie Clip instances are really objects. It’s easy to understand how each Movie Clip instance has unique properties. For example, each instance of a clip on the Stage can have a different _x property and _y property. There are several built-in properties of clips that can vary between each instance. Objects also have methods. Methods are commands or functions that operate on an individual object instance. A great example of a method is the gotoAndStop() action. If you said someClip.gotoAndStop(2);, for example, the clip instance named “someClip” would jump to frame 2. gotoAndStop() is a method of the Movie Clip object.

As stated earlier, there are other built-in objects and even a way for you to create your own objects, but none has such a physical presence as a clip instance. Many of the other objects require you to first create an instance of the object (called instantiating) by assigning the value of a variable to an Object data type—maybe oneObject=new Color(). Then you can change properties of the oneObject instance or apply methods to it. (Color happens to be one of the built-in objects and it comes standard with many properties and methods.) If you were making your own object, you’d first have to define the properties and methods you plan to have. It gets very involved, which is why I have several chapters on the subject, but the usage of objects is always the same: You put the Object data type into a variable, and then you act on that variable instance. If you want more copies of the object, just stuff them into other variables. Each variable’s value is an object. It’s pretty weird because you never “see” anything unless you proceed to affect something onscreen. Just return to the concept that a clip instance is an object and you should have an easier time.

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