BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


ActionScript: The Definitive Guide
ActionScript: The Definitive Guide Mastering Flash Programming

By Colin Moock

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: A Gentle Introduction for Non-Programmers
I'm going to teach you to talk to Flash.
Not just to program in Flash but to say things to it and to listen to what it has to say in return. This is not a metaphor or simply a rhetorical device. It's a philosophical approach to programming.
Programming languages are used to send information to and receive information from computers. They are collections of vocabulary and grammar used to communicate, just like human languages. Using a programming language, we tell a computer what to do or ask it for information. It listens, tries to perform the requested actions, and gives responses. So while you may think you are reading this book in order to "learn to program," you are actually learning to communicate with Flash. But, of course, Flash doesn't speak English, French, German, or Cantonese. Flash's native language is ActionScript, and you're going to learn to speak it.
Learning to speak a computer language is sometimes considered synonymous with learning to program. But there is more to programming than learning a language's syntax. What would it be like if Flash could speak English—if we didn't need to learn ActionScript in order to communicate with it?
What would happen if we were to say, "Flash, make a ball bounce around the screen?"
Flash couldn't fulfill our request because it doesn't understand the word "ball." Okay, okay, that's just a matter of semantics. What Flash expects us to describe is the objects in the world it knows: movie clips, buttons, frames, and so on. So, let's rephrase our request in terms that Flash recognizes and see what happens: "Flash, make the movie clip named ball_one bounce around the screen."
Flash still can't fulfill our request without more information. How big should the ball be? Where should it be placed? In which direction should it begin traveling? How fast should it go? Around which part of the screen should it bounce? For how long? In two dimensions or three? Hmm . . . we weren't expecting all these questions. In reality, Flash doesn't ask us these questions. Instead, when Flash can't understand us, it just doesn't do what we want it to, or it yields an error message. For now, we'll pretend Flash asked us for more explicit instructions, and reformulate our request as a series of steps:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Some Basic Phrases
On the first day of any language school you'd expect to learn a few basic phrases ("Good day," "How are you," etc.). Even if you're just memorizing a phrase and don't know what each word means, you can learn the effect of the phrase and can repeat it to produce that effect. Once you've learned the rules of grammar, expanded your vocabulary, and used the words from your memorized phrases in multiple contexts, you can understand your early phrases in a richer way. The rest of this chapter will be much like that first day of language school—you'll see bits and pieces of code, and you'll be introduced to some fundamental programming grammar. The rest of the book will build on that foundation. You may want to come back to this chapter when you've finished the book to see just how far you've traveled.
For our first exercise, we'll learn how to add four simple lines of code to a Flash movie. Nearly all ActionScript programming takes place in the Actions panel. Any instructions we add to the Actions panel are carried out by Flash when our movie plays. Open the Actions panel now by following these steps:
  1. Launch Flash with a new blank document.
  2. On the main timeline, select frame 1 of layer 1.
  3. Select Window Actions.
The Actions panel is divided into two sections: the Script pane (on the right) and the Toolbox pane (on the left). The Script pane houses all our code. The Toolbox pane provides us with quick access to the Actions, Operators, Functions, Properties, and Objects of ActionScript. You'll likely recognize the Basic Actions, shown in Figure 1.1, from prior Flash versions.
Figure 1.1: Flash 5 Basic Actions
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Further ActionScript Concepts
You've already been introduced to many of the fundamental elements that make up ActionScript: data, variables, operators, statements, functions, and arguments. Before we delve deeper into those topics, let's sketch out the rest of ActionScript's core features.
To most computer users, a program is synonymous with an application, such as Adobe Photoshop or Macromedia Dreamweaver. Obviously, that's not what we're building when we program in Flash. Programmers, on the other hand, define a program as a collection of code (a "series of statements"), but that's only part of what we're building.
A Flash movie is more than a series of lines of code. Code in Flash is intermingled with Flash movie elements, like frames and buttons. We attach our code to those elements so that it can interact with them.
In the end, there really isn't such a thing as a Flash "program" in the classic sense of the term. Instead of complete programs written in ActionScript, we have scripts : code segments that give programmatic behavior to our movie, just as JavaScript scripts give programmatic behavior to HTML documents. The real product we're building is not a program but a complete movie (including its code, timelines, visuals, sound, and other assets).
Our scripts include most of what you'd see in traditional programs without the operating-system-level stuff you would write in languages like C++ or Java to place graphics on the screen or cue sounds. We're spared the need to manage the nuts 'n' bolts of graphics and sound programming, which allows us to focus most of our effort on designing the behavior of our movies.
The statements of a script, as we've learned, contain the script's instructions. But most instructions are pretty useless without data. When we set a variable, for example, we assign some data as its value. When we use the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building a Multiple-Choice Quiz
Now that we've explored the basic principles of ActionScript, let's apply those principles in the context of a real Flash movie. We'll start our applied study of Flash programming by creating a multiple-choice quiz using very simple programming techniques, most of which you've already learned. We'll revisit our quiz in later chapters to see how it can be improved after learning more advanced programming concepts. We'll eventually make the code more elegant so that it's easier to extend and maintain, and we'll add more features to our quiz so that it can easily handle any number of questions.
The finished .fla file for this quiz may be found in the online Code Depot. This is a lesson in Flash programming, not Flash production. It is assumed that you are already comfortable creating and using buttons, layers, frames, keyframes, and the Text tool. The quiz shows real-world applications of the following aspects of ActionScript programming:
  • Variables
  • Controlling the playhead of a movie with functions
  • Button event handlers
  • Simple conditionals
  • Text field variables for on-screen display of information
Our quiz, part of which is shown in Figure 1.4, will have only two questions. Each question comes with three multiple-choice answers. Users submit their answers by clicking the button that corresponds to their desired selections. The selections are recorded in a variable so that they may be used to grade the user's score. When all the questions have been answered, the number of correct answers is tallied and the user's score is displayed.
Figure 1.4: A Flash quiz
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Onward!
So how does it feel? You've learned a bunch of phrases, some grammar, some vocabulary, and even had a drawn-out conversation with Flash (the multiple-choice quiz). Quite a rich first day of language school, I'd say.
As you can see, there's a lot to learn about ActionScript, but you can also do quite a bit with just a little knowledge. Even the amount you know now will give you plenty to play around with. Over the rest of this book, we'll reinforce the fundamentals you've learned by exploring them in more depth and showing them in concert with real examples. Of course, we'll also cover some topics that haven't even been introduced yet.
Remember: think communication, think cooperation, and speak clearly. And if you find yourself doing any fantastically engaging work or art that you'd like to share with others, send it over to me at http://www.moock.org/webdesign/flash/contact.html.
Now that you have a practical frame of reference, you'll be better able to appreciate and retain the foundational knowledge detailed over the next few chapters. It will give you a deeper understanding of ActionScript, enabling you to create more complex movies.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Variables
In a typical scripted movie, we have to track and manipulate everything from frame numbers to a user's password to the velocity of a photon torpedo fired from a spaceship. In order to manage and retrieve all that information, we need to store it in variables, the primary information-storage containers of ActionScript.
A variable is a like a bank account that, instead of holding money, holds information (data). Creating a new variable is like setting up a new account; we establish a place to store something we'll need in the future. And just as every bank account has an account number, every variable has a name associated with it that is used to access the data in the variable.
Once a variable is created, we can put new data into it as often as we want—much like depositing money into an account. Or we can find out what's in a variable using the variable's name—much like checking an account balance. If we no longer need our variable, we can "close the account" by deleting the variable.
The key feature to note is that variables let us refer to data that either changes or is calculated when a movie plays. Just as a bank account's number remains the same even though the account balance varies, a variable's name remains fixed even though the data it contains may change. Using that fixed reference to access changing content, we can perform complex calculations, keep track of cards in a card game, save guest book entries, or send the playhead to different locations based on changing conditions.
Is that a gleam of excitement I see in your eye? Good, I thought I might have lost you with all that talk about banks. Let's start our exploration of variables by seeing how to create them.
Creating a variable is called declaration. Declaration is the "open an account" step of our bank metaphor, where we formally bring the variable into existence. When a variable is first declared, it is empty—a blank page waiting to be written upon. In this state, a variable contains a special value called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Variables (Declaration)
Creating a variable is called declaration. Declaration is the "open an account" step of our bank metaphor, where we formally bring the variable into existence. When a variable is first declared, it is empty—a blank page waiting to be written upon. In this state, a variable contains a special value called undefined (indicating the absence of data).
To declare a new variable, we use the var statement. For example:
var speed;
var bookTitle;
var x;
The word var tells the interpreter that we're declaring a variable, and the text that follows, such as speed, bookTitle, or x, becomes our new variable's name. We can create variables anywhere we can attach code: on a keyframe, a button, or a movie clip.
We can also declare several variables with one var statement, like this:
var x, y, z;
However, doing so impairs our ability to add comments next to each variable.
Once a variable has been created, we may assign it a value, but before we learn how to do that, let's consider some of the subtler details of variable declaration.
Many programming languages require variables to be declared before data may be deposited into them; failure to do so would cause an error. ActionScript is not that strict. If we assign a value to a variable that does not exist, the interpreter will create a new variable for us. The bank, to continue that analogy, automatically opens an account when you try to make your first deposit.
This convenience comes at a cost, though. If we don't declare our variables ourselves, we have no central inventory to consult when examining our code. Furthermore, explicitly declaring a variable with a var statement can sometimes yield different results than allowing a variable to be declared implicitly (i.e., automatically). It's safest to declare first and use later (i.e., explicit declaration), as shown throughout this book.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Assigning Variables
Now comes the fun part—putting some data into our variables. If you're still playing along with the bank analogy, this is the "deposit money into our account" step. To assign a variable a value, we use:
               variableName = value;
where variableName is the name of a variable, and value is the data we're assigning to that variable. Here's an applied example:
bookTitle = "ActionScript: The Definitive Guide";
On the left side of the equal sign, the word bookTitle is the variable's name (its identifier). On the right side of the equal sign, the phrase "ActionScript: The Definitive Guide" is the variable's value —the datum you're depositing. The equal sign itself is called the assignment operator. It tells Flash that you want to assign (i.e., deposit) whatever is on the right of the equal sign to the variable shown on the left. If the variable on the left doesn't exist yet, Flash creates it (though relying on the interpreter to implicitly create variables isn't recommended).
Here are two more variable assignment examples:
speed = 25;
output = "thank you";
The first example assigns the integer 25 to the variable speed, showing that variables can contain numbers as well as text. We'll see shortly that they can contain other kinds of data as well. The second example assigns the text "thank you" to the variable output. Notice that we use straight double quotation marks (" ") to delimit a text string in ActionScript.
Now let's look at a slightly more complicated example that assigns y the value of the expression 1 + 5:
y = 1 + 5;
When the statement y = 1 + 5; is executed, 1 is first added to 5, yielding 6, and then 6 is assigned to y. The expression on the right side of the equal sign is evaluated (calculated or resolved) before setting the variable on the left side equal to that result. Here we assign an expression that contains the variable y to another variable, z:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Changing and Retrieving Variable Values
After we've created a variable, we may assign and reassign its value as often as we like, as shown in Example 2.1.
Example 2.1. Changing Variable Values
var firstName;                   // Declare the variable firstName
firstName = "Graham";            // Set the value of firstName
firstName = "Gillian";           // Change the value of firstName
firstName = "Jessica";           // Change firstName
                   again
firstName = "James";             // Change firstName
                   again
var x = 10;                      // Declare x and assign a numeric value
x = "loading...please wait...";  // Assign x a text value
Notice that we changed the variable x's datatype from numeric to text data by simply assigning it a value of the desired type. Some programming languages don't allow the datatype of a variable to change but ActionScript does.
Of course, creating variables and assigning values to them is useless if you can't retrieve the values later. To retrieve a variable's value, simply use the variable's name wherever you want its value to be used. Anytime a variable's name appears (except in a declaration or on the left side of an assignment statement), the name is converted to the variable's value. Here are some examples:
newX = oldX + 5;  // Set newX to the value of oldX plus 5
ball._x = newX;   // Set the horizontal position of the
                  // ball movie clip to the value of newX
trace(firstName); // Display the value of firstName in the Output window
Note that in the expression ball._x, ball is a movie clip's name, and the ._x indicates its x-coordinate property (i.e., horizontal position on stage). We'll learn more about properties later. The last line, trace(firstName), displays a variable's value while a script is running, which is handy for debugging your code.
Occasionally we may wish to verify that a variable has been assigned a value before we make reference to it. As we learned earlier, a variable that has been declared but never assigned a value contains the special "non-value,"
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Types of Values
The data we use in ActionScript programming comes in a variety of types. So far we've seen numbers and text, but other types include Booleans, arrays, functions, and objects. Before we cover each datatype in detail, let's examine some datatype issues that specifically relate to variable usage.
Any ActionScript variable can contain any type of data, which may seem unremarkable, but the ability to store any kind of data in any variable is actually a bit unusual. Languages like C++ and Java use typed variables; each variable can accept only one type of data, which must be specified when the variable is declared. ActionScript variables are automatically typed—when we assign data to a variable, the interpreter sets the variable's datatype for us.
Not only can ActionScript variables contain any datatype, they can also dynamically change datatypes. If we assign a variable a new value that has a different type than the variable's previous value, the variable is automatically retyped. So the following code is legal in ActionScript:
x = 1;                   // x is a number
x = "Michael";           // x is now a string
x = [4, 6, "hello"];     // x is now an array
x = 2;                   // x is a number again
In languages like C++ or Java that do not support automatic retyping, data of the wrong type would be converted to the variable's existing datatype (or would cause an error if conversion could not be performed). Automatic and dynamic typing have some important ramifications that we'll consider in the following sections.
In some contexts, ActionScript expects a specific type of data. If we use a variable whose value does not match the expected type, the interpreter attempts to convert the data. For example, if we use a text variable where a number is needed, the interpreter will try to convert the variable's text value to a numeric value for the sake of the current operation. In Example 2.2,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variable Scope
Earlier we learned how to create variables and retrieve their values using variables attached to a single frame of the main timeline of a Flash document. When a document contains multiple frames and multiple movie clip timelines, variable creation and value retrieval becomes a little more complicated.
To illustrate why, let's consider several scenarios.
Suppose we were to create a variable, x, in frame 1 of the main timeline. After creating x, we set its value to 10:
var x;
x = 10;
Then, in the next frame (frame 2), we attach the following code:
trace(x);
When we play our movie, does anything appear in the Output window? We created our variable in frame 1, but we're attempting to retrieve its value in frame 2; does our variable still exist? Yes.
When you define a variable on a timeline, that variable is accessible from all the other frames of that timeline.
Suppose we create and set x as we did in Scenario 1, but instead of placing the variable-setting code on frame 1 directly, we place it on a button in frame 1. Then, on frame 2, we attach the same code as before:
trace(x);
Does Scenario 2 also work? Yes. Because x is attached to our button, and our button is attached to the main timeline, our variable is indirectly attached to the main timeline. We may, therefore, access the variable from frame 2 as we did before.
Suppose we create a variable named secretPassword on frame 1 of the main timeline. When the movie plays, the user must guess the password in order to gain access to a special section of the movie.
In addition to declaring secretPassword on frame 1, we create a function that compares the user's guess to the real password. Here's our code:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Some Applied Examples
We've had an awful lot of variable theory. How about showing some of these concepts in use? The following examples provide three variable-centric code samples. Refer to the comments for an explanation of the code.
Example 2.6 chooses a random destination for the playhead of a movie.
Example 2.6. Send the Playhead to a Random Frame on the Current Timeline
var randomFrame;            // Stores the randomly picked frame number
var numFrames;              // Stores the total number of frames on the timeline
numFrames = _totalframes;   // Assign _totalframes property to numFrames

// Pick a random frame
randomFrame = Math.floor(Math.random( ) * numFrames + 1);

gotoAndStop(randomFrame);   // Send playhead to chosen random frame
Example 2.7 determines the distance between two clips. A working version of this example is available from the online Code Depot.
Example 2.7. Calculate the Distance Between Two Movie Clips
var c;         // A convenient reference to the circle clip object
var s;         // A convenient reference to the square clip object
var deltaX;    // The horizontal distance between c and s
var deltaY;    // The vertical distance between c and s
var dist;      // The total distance between c and s

c = _root.circle;       // Get reference to the circle clip
s = _root.square;       // Get reference to the square clip
deltaX = c._x - s._x;   // Compute the horizontal distance between the clips
deltaY = c._ y - s._ y;   // Compute the vertical distance between the clips

// The distance is the root of (deltaX squared plus deltaY squared).
dist = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));

// Tidy references are much more readable than the alternative:
dist = Math.sqrt(((_root.circle._x - _root.square._x) * (_root.circle._x - 
_root.square._x)) + ((_root.circle._ y - _root.square._ y) * (_root.circle._ y - 
_root.square._ y)));
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Onward!
Now that we know all there is to know about storing information in variables, it's time we learn something more about the content that variables store: data. Over the next three chapters, we'll learn what data is, how it can be manipulated, and why it's an essential part of nearly everything we build with ActionScript.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Data and Datatypes
Having worked with variable values in Chapter 2, we've already had a casual introduction to data, the information we manipulate in our scripts. In this chapter, we'll explore data in more depth, learning how ActionScript defines, categorizes, and stores data. We'll also see how to create and classify data.
In the broadest sense, data is anything that can be stored by a computer, from words and numbers to images, video, and sound. All computer data is stored as a sequence of ones and zeros, which you might recognize from high-tech marketing materials:
010101010101010110101011011010101010101010000010101010101011010101010
101010101010101011101010101010101010101010101010111110101010101010101
010101010101010101010101011101010101010101010101010101010101010101010
Data is information in its crude state—raw and meaningless. Information, on the other hand, has meaning. Consider, for example, the number 8008898969. As raw data it isn't very meaningful, but when we classify it semantically as the telephone number (800) 889-8969, the data becomes useful information.
In this chapter we'll see how to add meaning to raw computer data so that it becomes human-comprehensible information.
How do we store information as raw data in a computer without losing meaning? By categorizing our data and defining its datatype, we give it context that defines its meaning.
For example, suppose we have three numbers: 5155534, 5159592, and 4593030. By categorizing our data—as, say, a phone number, fax number, and parcel tracking number—the context (and, hence, the meaning) of our data is preserved. When categorized, each of the otherwise-nondescript seven-digit numbers becomes meaningful.
Programming languages use datatypes to provide rudimentary categories for our data. For example, nearly all programming languages define datatypes to store and manipulate text (a.k.a. strings) and numbers. To distinguish between multiple numbers, we can use well-conceived variable names, such as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Data Versus Information
In the broadest sense, data is anything that can be stored by a computer, from words and numbers to images, video, and sound. All computer data is stored as a sequence of ones and zeros, which you might recognize from high-tech marketing materials:
010101010101010110101011011010101010101010000010101010101011010101010
101010101010101011101010101010101010101010101010111110101010101010101
010101010101010101010101011101010101010101010101010101010101010101010
Data is information in its crude state—raw and meaningless. Information, on the other hand, has meaning. Consider, for example, the number 8008898969. As raw data it isn't very meaningful, but when we classify it semantically as the telephone number (800) 889-8969, the data becomes useful information.
In this chapter we'll see how to add meaning to raw computer data so that it becomes human-comprehensible information.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Retaining Meaning with Datatypes
How do we store information as raw data in a computer without losing meaning? By categorizing our data and defining its datatype, we give it context that defines its meaning.
For example, suppose we have three numbers: 5155534, 5159592, and 4593030. By categorizing our data—as, say, a phone number, fax number, and parcel tracking number—the context (and, hence, the meaning) of our data is preserved. When categorized, each of the otherwise-nondescript seven-digit numbers becomes meaningful.
Programming languages use datatypes to provide rudimentary categories for our data. For example, nearly all programming languages define datatypes to store and manipulate text (a.k.a. strings) and numbers. To distinguish between multiple numbers, we can use well-conceived variable names, such as phoneNumber and faxNumber. In more complex situations, we can create our own custom data categories with objects and object classes as covered later. Before we think about making our own data categories, let's see which categories come built into ActionScript.
When programming, we may want to store a product name, a background color, or the number of stars to be placed in a night sky. We use the following ActionScript datatypes to store our data:
  • For text sequences like "hi there," ActionScript provides the string datatype. A string is a series of characters (alphanumerics and punctuation).
  • For numbers, such as 351 and 7.5, ActionScript provides the number datatype. Numbers are used for counting and for mathematical equations.
  • For logical decisions, ActionScript provides the Boolean datatype. With Boolean data, we can represent or record the status of some condition or the result of some comparison. Boolean data has only two legal values:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating and Categorizing Data
There are two ways to create a new datum with ActionScript, both methods requiring the use of expressions—phrases of code that represent data in our scripts.
A literal expression (or literal for short) is a series of letters, numbers, and punctuation that is the datum. A data literal is a verbatim description of data in a program's source code. This contrasts with a variable, which is a container that merely holds a datum. Each datatype defines its own rules for the creation of literals. Here are some examples of literals:
"loading...please wait"  // A string literal
1.51                     // A numeric literal
["jane", "jonathan"]     // An array literal
Note that movie clips cannot be represented by literals, but are referred to by instance names.
We can also generate data programmatically with a complex expression. Complex expressions represent data as a phrase of code with a value that must be calculated or computed, not taken literally. The calculated value is the datum being represented. For example, each of these complex expressions results in a single datum:
1999 + 1       // Yields the datum 2000
"hi " + "ma!"  // Yields the datum "hi ma!"
firstName      // Yields the value of the variable firstName
_currentframe  // Yields the frame number of the playhead's current position
new Date( )     // Yields a new Date object with the current date and time
Notice that an individual literal expression like 1999 or 1 can be a valid part of a larger complex expression, as in 1999 + 1.
Whether we use a literal expression or a complex expression to create data, we must store every datum that we want to use later. The result of the expression "hi" + "ma!" is lost unless we store it, say, in a variable. For example:
// This datum is fleeting, and dies immediately after it's created
"hi " + "ma";

// This datum is stored in a variable and can be
// accessed later via the variable 
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Datatype Conversion
Take a closer look at the example from the previous section. In that example, each datum—"1" and 2—belonged to its own datatype; the first was a string and the second a number. We saw that the interpreter joined the two values together to form the string "12". Note that the interpreter first had to convert the number 2 into the string "2". Only after that automatic conversion was performed could the value "2" be joined (concatenated) to the string "1".
Datatype conversion simply means changing the type of a datum. Not all datatype conversions are automatic; we may also change a datum's type explicitly in order to override the default datatyping that ActionScript would otherwise perform.
Whenever we use a value in a context that does not match its datatype, the interpreter attempts a conversion. That is, if the interpreter expects data of type A, and we provide data of type B, the interpreter will attempt to convert our type B data into type A data. For example, in the following code we use the string "Flash" as the righthand operand of the subtraction operator. Since only numbers may be used with the subtraction operator, the interpreter attempts to convert the string "Flash" into a number:
999 - "Flash";
Of course, the string "Flash" can't be successfully converted into any legitimate number, so it is converted into the special numeric data value NaN (i.e., Not-a-Number). NaN is a legal value of the number datatype, intended specifically to handle such a situation. With "Flash" converted to NaN, our expression ends up looking like this to the interpreter (though we never see this internal step):
999 - NaN;
Both operands of the subtraction operator are now numbers, so the operation can proceed: 999 - NaN yields the value NaN, which is the final value of our expression.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Primitive Data Versus Composite Data
So far we've been working mostly with numbers and strings, which are the most common primitive datatypes. Primitive datatypes are the basic units of a language; each primitive value contains a single datum (as opposed to an array of multiple items) and describes that datum literally. Primitive data is very straightforward.
ActionScript supports these primitive datatypes: number, string, boolean, undefined, and null. ActionScript does not have a separate single-character datatype (i.e., char) as found in C/C++.
Primitive datatypes are, as their name suggests, simple. They can hold text messages, frame numbers, movie clip size values, and so on, but they don't readily accommodate higher levels of complexity. For more elaborate data handling—such as simulating the physics of a dozen bouncing balls or managing a quiz with 500 questions and answers—we turn to composite datatypes. Using composite data, we can manage multiple pieces of related data as a single datum.
ActionScript supports the following composite datatypes: array, object, and movieclip. Functions are technically a type of object and are therefore considered composite data, but we rarely manipulate them as such. See Chapter 9, for more about functions as a datatype.
Whereas a single number is a primitive datum, a list (i.e., an array) of multiple numbers is a composite datum. Here's a practical example of how composite datatypes are useful: Suppose we wanted to track the profile of a customer named Derek. We could create a series of variables that store Derek's attributes as primitive values, like this:
var custName = "Derek";
var custTitle = "Coding Genius";
var custAge = 30;
var custPhone = "416-222-3333";
However, this format gets pretty cumbersome once we add even a few more customers. We're forced to use sequentially named variables to keep track of everything—cust1Name, cust2Name, cust1Title, cust2Title, and so on. Yuck! But if we use an array, we can store our information much more efficiently:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Onward!
Content preview·

Return to ActionScript: The Definitive Guide