BUY THIS BOOK
Add to Cart

Print Book $54.95


Add to Cart

Print+PDF $71.44

Add to Cart

PDF $43.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £38.95

What is this?

Looking to Reprint or License this content?


ActionScript for Flash MX: The Definitive Guide
ActionScript for Flash MX: The Definitive Guide, Second Edition By Colin Moock
December 2002
Pages: 1088

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: A Gentle Introductionfor Nonprogrammers
I'm going to teach you to talk to Flash.
Not just to program in Flash, but to say things to it and 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 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 (F9). (Note that we use the " " symbol to separate a menu name from a menu option; you should select the "Actions" item from Flash's "Windows" menu.)
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. In Normal Mode, the top of the Script pane includes a Parameters pane that simplifies code entry for novices. The Toolbox pane provides us with quick-reference access to the ActionScript language. You'll likely recognize the Movie Control Actions, shown in Figure 1-1, from prior Flash versions.
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 seen 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 MX. 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, such as frames, movie clips, graphics, and buttons. 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 Flash movie (the exported .swf file, 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 and 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 trace( ) command, we pass data as an argument for display in the Output window. Data is the content we manipulate in our ActionScript code. Throughout your scripts, you'll retrieve, assign, store, and generally sling around a lot of data.
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 can be found in the online Code Depot, cited in the Preface. This is a lesson in Flash programming, not Flash production. I assume that you are already comfortable creating and using buttons, layers, frames, keyframes, and the Text tool. If not, consult the Flash Help documentation. The quiz shows a real-world application of the following aspects of ActionScript programming:
  • Variables
  • Controlling the playhead of a movie with functions
  • Button event handlers
  • Simple conditionals
  • Text field objects used 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 that is later used to grade the quiz. When all the questions have been answered, the number of correct answers is tallied, and the user's score is displayed.
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. Throughout 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/contact/.
Now that you have a practical frame of reference, you'll be 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 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 by using the variable's name—much like checking an account's 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 slate 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 slate 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 moniker 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.
If you enter code in the Actions panel while on a frame that is not a keyframe, the code is attached to the nearest preceding keyframe.
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 can 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 you to declare variables before depositing data into them; failure to do so causes an error. ActionScript is not that strict. If we assign a value to a variable that does not exist, the interpreter creates 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
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 Values to 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 value to a variable, 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 example:
bookTitle = "ActionScript for Flash MX: The Definitive Guide";
On the left side of the equals sign, the word bookTitle is the variable's name (its identifier). On the right side of the equals sign, the phrase "ActionScript for Flash MX: The Definitive Guide" is the variable's value—the datum you're depositing. The equals sign is called the assignment operator. It tells Flash that you want to assign (i.e., deposit) whatever is on the right of the equals 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 create variables implicitly 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 variables 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 the value of the expression 1 + 5 to the variable y:
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 equals sign is evaluated (calculated or resolved) before assigning the result to the variable on the left side. Here, we assign an expression that contains the variable y to another 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!
Changing and Retrieving Variable Values
After we create a variable, we can 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 it 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. Note that _x is a built-in property representing a movie clip's horizontal position with no relation to the variable named x used in preceding examples (see the "Variable Naming Styles" sidebar in Chapter 1, and see MovieClip._x in the Language Reference).
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 ._x indicates its x-coordinate property (i.e., horizontal position on stage). We'll learn more about properties later. The last line,
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 relate specifically 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 strictly 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 retyped automatically. 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 that do not perform automatic retyping, such as C++ and Java, data of the wrong type is converted to the variable's existing datatype (or it causes an error if conversion cannot be performed). By comparison, VB.NET allows the programmer to decide whether the compiler should enforce strict typing. Strict typing may seem cumbersome, but it can prevent the errors that unsuspecting programmers may encounter due to automatic and dynamic typing, which 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 to the necessary type. 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. But all our variables were 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 the use of timeline variables, let's consider two simple scenarios.

Section 2.5.1.1: Scenario 1: Accessing a value defined earlier on the same timeline

What happens when we define a variable in one frame of a timeline and try to access it later?
Suppose we 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. The Output window displays 10.
When you define a variable on a timeline, that variable is accessible from all the other frames of that timeline.

Section 2.5.1.2: Scenario 2: Accessing a value defined later on the same timeline

What happens if we try instead to access a variable before the frame in which it is assigned a value?
Suppose we add the following code to frame 30 of a movie's main timeline:
password = "let_me_in";
gotoAndStop(15);
and on frame 15 we add:
trace(password);
When the movie plays, we see the following in the Output window:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Loading External Variables
While most variables are created directly inside Flash, it's also common to load variables from an external text file, server script, or web page. Loading external variables does not mean simply assigning a value from an external source to existing variables. Loading external variables actually creates new variables at runtime. The following entries in the ActionScript Language Reference explain various variable-loading techniques:
  • LoadVars
  • loadVariables( )
  • fscommand( )
Additionally, in some browsers, JavaScript can set a variable in Flash at runtime using the syntax:
               movieObj.SetVariable("/someClip:firstName", "Colin");
where movieObj is an object reference to the Flash movie embedded in the page. This technique works only in the following browsers:
  • Internet Explorer on Windows
  • Netscape 4 on Windows, Macintosh, and Linux
  • Netscape 6.2 with Flash Player 6.0.40.0 (or higher) on Windows, Macintosh, and Linux
For complete details, see:
http://www.moock.org/webdesign/flash/fscommand/
Similarly, an HTML document's <OBJECT> and <EMBED> tags can create variables in a Flash movie, when the movie initially loads, via the FlashVars parameter or a query string. Variables passed to a Flash movie via FlashVars or a query string must be URL-encoded according to the rules described in the LoadVars class in the Language Reference. The following code uses the FlashVars parameter to create the variables
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. The following examples provide three variable-centric code samples that show some of these concepts in use. Refer to the comments within the code for an explanation of each line of code.
Example 2-6 sends the playhead of a movie clip to a random destination.
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 in the clip
numFrames = this._totalframes;   // Store the current movie clip's 
                                 // _totalframes property in numFrames
// Pick a random frame
randomFrame = Math.floor(Math.random( ) * numFrames + 1);
this.gotoAndStop(randomFrame);   // Send playhead of current movie clip 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 square root of (deltaX squared plus deltaY squared).
dist = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
// Using variables, the code above creates tidy references that
// are much more readable than the alternative, shown below:
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 the fundamentals of storing information in variables, including advanced topics such as variable scope, 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, you'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 explore 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 1s and 0s, which you might recognize from high-tech marketing materials:
010101010101010110101011011010101010101010000010101010101011010101010
101010101010101011101010101010101010101010101010111110101010101010101
010101010101010101010101011101010101010101010101010101010101010101010
Data is information in its crude state—raw and meaningless. Semantics give information 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.
This chapter shows how to add meaning to raw computer data so that it becomes human-comprehensible information.
How do we store information as raw data 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 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 1s and 0s, which you might recognize from high-tech marketing materials:
010101010101010110101011011010101010101010000010101010101011010101010
101010101010101011101010101010101010101010101010111110101010101010101
010101010101010101010101011101010101010101010101010101010101010101010
Data is information in its crude state—raw and meaningless. Semantics give information 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.
This chapter shows 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 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 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 in Chapter 12. 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:
string
For text sequences such as "hi there". A string is a series of characters (alphanumerics and punctuation).
number
For numbers, such as 351 and 7.5. Numbers are used for counting and for mathematical equations.
boolean
For logical decisions. 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, and both methods require the use of expressions—phrases of code that represent data in 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 merely a container that holds a datum. Each datatype defines its own rules for the creation of literals. For example, string literals are enclosed in quotes, whereas numeric literals are not. Here are some examples of literals:
"loading...please wait"  // A string literal
1.51                     // A numeric literal
["jane", "jonathan"]     // An array literal
{x: 10, y: 15}           // An object 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 are phrases 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 numeric datum 2000
"1999" + "1"   // Yields the string datum "19991"
"hi " + "ma!"  // Yields the string 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, such as 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:
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 was 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 datatype conversion that ActionScript would otherwise perform. Explicit conversion is known as typecasting, or simply casting.
Whenever we use a value in a context that does not match the expected 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 right-hand 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 a 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 interim 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 represents a single datum (as opposed to an array of multiple items) and holds that datum directly, rather than holding its address elsewhere in memory.
ActionScript supports these primitive datatypes: number, string, boolean, undefined, and null. ActionScript does not have a separate single-character datatype (e.g., char) as found in C/C++ (strings are a primitive datatype in ActionScript, and not arrays of chars as they are in C/C++).
Primitive datatypes are, as their name suggests, simple. They can hold text messages, frame numbers, secret passwords, 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. Technically, functions are 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 want to store the name of a customer named Derek. We can create a variable that stores Derek's name as a primitive value, like this:
var custName = "Derek";
However, this approach gets pretty cumbersome once we add more customers. We're forced to use sequentially named variables to keep track of our customers—cust1Name, cust2Name, cust3Name, 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!
Copying, Comparing, and Passing Data
There are three fundamental ways to manipulate data; we can copy it (e.g., assign the value of variable x to variable y), compare it (e.g., check whether x equals y), and pass it (e.g., supply a variable to a function as an argument). Primitive data values are copied, compared, and passed quite differently than composite data. When primitive data is copied to a variable, that variable gets its own unique and private copy of the data, stored separately in memory. Hence, the following lines of code cause the string "Dave" to be stored twice in memory, once in the memory location reserved for name1 and again in the location reserved for name2:
name1 = "Dave";
name2 = name1;
We say that primitive data is copied by value because the data's literal value is stored in the memory location allotted to the variable. In contrast, when composite data is copied to a variable, only a reference to the data (and not the actual data) is stored in the variable's memory slot. That reference tells the interpreter where the actual data is kept (i.e., its address in memory). When a variable that contains composite data is copied to another variable, it is the reference (often called a pointer) and not the data itself that is copied. Hence, composite data is said to be copied by reference.
This makes good design sense, because it would be grossly inefficient to duplicate large arrays and other composite datatypes, but it has important consequences for our code. When multiple variables are assigned the same piece of composite data as their value, each variable does not store a unique copy of the data (as it would if the data were primitive). Rather, multiple variables can point to one copy of the composite data. If the value of the data changes, all the variables that point to it reflect the updated value.
Let's see how this affects a practical application. When two variables refer to the same primitive data, each variable gets its own copy of the data. Here we assign the value 12 to 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!
Onward!
We've introduced data in ActionScript, and we're ready for deeper study. In Chapter 4, we'll study the number, string, boolean, undefined, and null datatypes. In Chapter 5, we'll explore how to manipulate data using operators. In later chapters, we'll study the complex datatypes, such as movieclips, arrays and objects.
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 4: Primitive Datatypes
Primitive data consists of simple characters or keywords, such as the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, or the strings "a", "b", and "c". As shown in Chapter 3, the primitive datatypes supported by ActionScript are number, string, boolean, undefined, and null. In this chapter, we'll explore how to define, examine, and change data of each type.
Numbers are used for counting, mathematics, and keeping track of numeric properties in our movies (such as the current frame of a movie clip or its location on the Stage). Let's see how numbers are defined and manipulated in ActionScript.
Most programming languages distinguish between two kinds of numbers: integers and floating-point numbers. An integer is a whole number that has no fractional component. Integers can be positive, negative, or the number 0. Floating-point numbers (floats for short) can include a fractional value represented after a decimal point, as in 0.56, 199.99, and 3.14159. So, 1, 34523, -3, 0, and -9999999 are integers, but 223.45 and -0.56 are floats.
We learned earlier that a literal is a direct representation of a single, fixed data value. The number type supports three kinds of literals: integer literals, floating-point literals, and special numeric values. The first two literal categories represent real numbers (numbers that have a fixed mathematical value); the third category comprises values that represent numeric concepts, such as infinity.
Integer literals, such as 1, 2, 3, 99, and -200, must follow these rules:
  • Integers may not contain a decimal point or fractional value.
  • Integers must not exceed the minimum or maximum legal numeric values of ActionScript. See 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!
The Number Type
Numbers are used for counting, mathematics, and keeping track of numeric properties in our movies (such as the current frame of a movie clip or its location on the Stage). Let's see how numbers are defined and manipulated in 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!
Integers and Floating-Point Numbers
Most programming languages distinguish between two kinds of numbers: integers and floating-point numbers. An integer is a whole number that has no fractional component. Integers can be positive, negative, or the number 0. Floating-point numbers (floats for short) can include a fractional value represented after a decimal point, as in 0.56, 199.99, and 3.14159. So, 1, 34523, -3, 0, and -9999999 are integers, but 223.45 and -0.56 are floats.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Numeric Literals
We learned earlier that a literal is a direct representation of a single, fixed data value. The number type supports three kinds of literals: integer literals, floating-point literals, and special numeric values. The first two literal categories represent real numbers (numbers that have a fixed mathematical value); the third category comprises values that represent numeric concepts, such as infinity.
Integer literals, such as 1, 2, 3, 99, and -200, must follow these rules:
  • Integers may not contain a decimal point or fractional value.
  • Integers must not exceed the minimum or maximum legal numeric values of ActionScript. See the MIN_VALUE and MAX_VALUE properties of the