1.1 Some Basic Phrases

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 1.  A Gentle Introductionfor Nonprogrammers

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.

1.1.1 Creating Code

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 figs/u2192.gif Actions (F9). (Note that we use the " figs/u2192.gif " 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.

Figure 1-1. Flash MX Movie Control Actions
figs/act2.0101.gif

But there's a lot more to discover in the Toolbox pane. This book covers Operators, Functions, Constants, Properties, and Objects in detail. Some of the Communications components are specific to Macromedia Flash Communication Server MX (Comm Server) and are beyond the scope of this book. Similarly, the Flash UI Components are not part of the core ActionScript language; Appendix G summarizes their properties and methods. Details on the Flash UI Components are available in Flash's documentation, under Help figs/u2192.gif Tutorials figs/u2192.gif Introduction to Components.

The Toolbox pane's book-like hierarchical menus can be used to create ActionScript code. However, in order to learn the syntax, principles, and structural makeup of ActionScript, we'll be entering all our code manually.

So-called Actions are more than just Actions they include various fundamental programming-language tools: variables, conditionals, loops, comments, function calls, and so forth. Although many of these are lumped together in one menu, the generic name Action obscures the programming structures' significance. We'll be breaking Actions down to give you a programmer's perspective on those structures. Throughout the book, I use the appropriate programming term to describe the Action at hand. For example, instead of writing, "Add a while Action," I'll write, "Create a while loop." Instead of writing, "Add an if Action," I'll write, "Add a new conditional." Instead of writing, "Add a play Action," I'll write, "Invoke the play( ) function (or method)." These distinctions are an important part of learning to speak ActionScript.

Ready to get your hands dirty? Let's say hello to Flash.

1.1.2 Say Hi to Flash

Before you can type code into the Actions panel, you must disengage the ActionScript autopilot. From the pop-up menu in the top right corner of the Actions panel, select Expert Mode, as shown in Figure 1-2. Howdya like that? You're already an expert.

Figure 1-2. Expert Mode selection
figs/act2.0102.gif

For brevity, I'll refer to any pop-up menu in one of Flash's panels as an "Options" menu for the remainder of the book. So I might write, "choose Options figs/u2192.gif Expert Mode in the Actions panel." While you're at it, you can also turn on line numbering using Options figs/u2192.gif View Line Numbers. See also Chapter 16 for more details on the Actions panel.

When you enter Expert Mode, the Parameters pane disappears from the top of the Actions panel (in Flash 5, the Parameters pane appeared at the bottom of the Actions panel while in Normal Mode). Don't worry we're not programming with menus, so we won't be needing it.

Next, select frame 1 of layer 1 in the main timeline.

Your ActionScript (a.k.a. code) must always be attached to a frame, movie clip, or button; selecting frame 1 causes subsequently created code to be attached to that frame. Flash executes the code attached to a frame when the timeline reaches that frame.

In Expert Mode, you can type directly into the Script pane on the right side of the Actions panel, which is where we'll be doing all our programming.

Here comes the exciting moment your first line of code. It's time to introduce yourself to Flash. Type the following into the Script pane:

var message = "Hi there, Flash!";

That line of code constitutes a complete instruction, known as a statement. On the line below it, type your second and third lines of code, shown following this paragraph. Replace your name here with your first name (whenever you see constant-width italicized code in this book it means you have to replace that portion of the code with your own content):

var firstName = "your name here"; trace (message);

Hmmm. Nothing has happened yet. That's because our code doesn't do anything until we export a .swf file and play our movie. Before we do that, let's ask Flash to say hi back to us. Type your fourth line of code under the lines you've already typed (man, we're really on a roll now . . . ):

trace ("Hi there, " + firstName + ", nice to meet you.");

Okay, Flash is ready to meet you. Select Control figs/u2192.gif Test Movie, and see what happens. Some text should appear in the Output window as shown in Figure 1-3.

Figure 1-3. Flash gets friendly
figs/act2.0103.gif

Pretty neat, eh? Let's find out how it all happened. To return to editing the .fla source file, close the window of the .swf file created by our test.

1.1.3 Keeping Track of Things ( Variables)

Remember how I said programming was really just communicating with a computer? Well, it is, but perhaps with a little less personality than I've been portraying so far. In your first line of code:

var message = "Hi there, Flash!";

you didn't really say hi to Flash. You said something more like this:

Flash, please remember a piece of information for me specifically, the phrase "Hi there, Flash!" I may need that information in the future, so please give it a label called message. If I ask you for message later, give me back the text "Hi there, Flash!"

Perhaps not as friendly as saying hi, but it illustrates one of the true foundations of programming: Flash can remember something for you, provided that you label it so that it can be found later. For example, in your second line of code, we had Flash remember your first name, and we named the reference to it firstName. Flash remembered your name and displayed it in the Output window, due to the trace( ) command, when you tested your movie.

The fact that Flash can remember things for us is crucial in programming. Flash can remember any type of data, including text (such as your name), numbers (such as 3.14159), and more complex kinds of information that we'll discuss later.

1.1.3.1 Official variable nomenclature

It's time for a few formal terms to describe how Flash remembers things. So far, you know that Flash remembers data. An individual piece of data is known as a datum. A datum (e.g., "Hi there, Flash!") and the label that identifies it (e.g., message) are together known as a variable. A variable's label is called its name, and a variable's datum is called its value. We say that the variable stores or contains its value. Note that "Hi there, Flash!" is surrounded by double quotation marks (quotes) to indicate that it is a string of text, not a number or some other kind of information (a.k.a. datatype).

In your first line of code, you specified the value of the variable message. The act of specifying the value of a variable is known as assigning the variable's value or simply assignment. But before you can assign a value to a variable, you should first create it (in ActionScript's cousin, JavaScript, you must create variables before using them). We formally bring variables into existence by declaring them using the special keyword var, which you used earlier.

So, in practice, here's how I might use more formal terms to instruct you to create the first line of code you created earlier: declare a new variable named message, and assign it the initial value "Hi there, Flash!" This means you should enter the following code in the Actions panel:

var message = "Hi there, Flash!";

1.1.4 The Wizard Behind the Curtain (the Interpreter)

Recall your first two lines of code:

var message = "Hi there, Flash!"; var firstName = "your name here";

In each of those statements, you created a variable and assigned a value to it. Your third and fourth lines, however, are a little different:

trace (message); trace ("Hi there, " + firstName + ", nice to meet you.");

These statements use the trace( ) command. You've already seen the effect of that command it caused Flash to display your text in the Output window. In the third line, Flash displayed the value of the variable message. In the last line, Flash also converted the variable firstName to its value (whatever you entered as your name) and stuck that into the sentence after the words "Hi there,". The trace( ) command, then, causes any specified data to appear in the Output window (which makes it handy for determining what's going on when a program is running).

The question is, what made the trace( ) command place your text in the Output window? When you create a variable or issue a command, you're actually addressing the ActionScript interpreter, which runs your programs, manages your code, listens for instructions, performs any ActionScript commands, executes your statements, stores your data, sends you information, calculates values, and even starts up the basic programming environment when a movie is loaded into the Flash Player.

The interpreter translates your ActionScript into a language that the computer understands and can use to carry out your instructions. During movie playback, the interpreter is always active, dutifully attempting to understand commands you give it. If the interpreter can understand your commands, it sends them to the computer's processor for execution. If a command generates a result, the interpreter provides that response to you. If the interpreter can't understand the command, it either sends you an error message or fails silently. The interpreter, hence, acts like a magic genie it carries out the orders you specify in your code and reports back to you from Flash when it's done. Like a genie, it always does exactly what you say, not necessarily what you think you mean!

Let's take a closer look at how the interpreter works by examining how it handles a simple trace( ) action.

Consider this command as the interpreter would:

trace ("Nice night to learn ActionScript.");

The interpreter immediately recognizes the keyword trace from its special list of legal command names. The interpreter also knows that trace( ) is used to display text in the Output window, so it also expects to be told what text to display. It finds, "Nice night to learn ActionScript." between parentheses following the word trace and thinks, "Aha! That's just what I need. I'll have that sent to the Output window right away!"

Note that the entire command is terminated by a semicolon (;). The semicolon acts like the period at the end of a sentence; with few exceptions, every ActionScript statement should end with a semicolon. With the statement successfully understood and all the required information in hand, the interpreter translates the command for the processor to execute, causing our text to appear in the Output window.

That's a gross oversimplification of the internal details of how a computer processor and an interpreter work, but it illustrates these points:

  • The interpreter is always listening for your instructions.

  • The interpreter has to read your code, letter by letter, and try to understand it. This is the same as you trying to read and understand a sentence in a book.

  • The interpreter reads your ActionScript using strict rules if the parentheses in our trace( ) statement were missing, for example, the interpreter wouldn't be able to understand what's going on, and the command would fail.

You've only just been introduced to the interpreter, but you'll be as intimate with it as you are with a lover before too long: lots of fights, lots of yelling "Why aren't you listening to me?!" and lots of beautiful moments when you understand each other perfectly. Strangely enough, my dad always told me the best way to learn a new language is to find a lover that speaks it. May I, therefore, be the first to wish you all the best in your new relationship with the ActionScript interpreter. From now on, I'll regularly refer to "the interpreter" interchangeably with "Flash" when describing how ActionScript instructions are carried out.

1.1.5 Extra Info Required (Arguments)

You've already seen one case in which we provided the interpreter with the text to display when issuing a trace( ) command. This approach is common; we'll often provide the interpreter with ancillary data required to execute a command. There's a special name for a datum sent to a command: an argument, or synonymously, a parameter. To supply an argument to a command, enclose the argument in parentheses, like this:

command(argument);

When supplying multiple arguments to a command, separate them with commas, like this:

command(argument1, argument2, argument3);

Supplying an argument to a command is known as passing the argument. For example, in the code phrase gotoAndPlay(5), the word gotoAndPlay is the name of the command, and 5 is the argument being passed (in this case the frame number). Some commands, such as stop( ), require parentheses but do not accept arguments. You'll learn why in Chapter 9, where we discuss functions in detail.

1.1.6 ActionScript's Glue (Operators)

Let's take another look at your fourth line of code, which contains this trace( ) statement:

trace ("Hi there, " + firstName + ", nice to meet you.");

See the + (plus) signs? They're used to join (concatenate) our text together and are but one of many available operators. The operators of a programming language are akin to conjunctions ("and," "or," "but," etc.) in human languages. They're devices used to combine and manipulate phrases of code. In the trace( ) example, the plus operator joins the quoted text "Hi there, " to the text contained in the variable firstName.

All operators link phrases of code together, manipulating those phrases in the process. Whether the phrases are text, numbers, or some other datatype, an operator almost always performs some kind of transformation. Very commonly, operators combine two things together, as the plus operator does. But other operators compare values, assign values, facilitate logical decisions, determine datatypes, create new objects, and provide various other handy services.

When used with two numeric operands, the plus sign (+) and the minus sign (-), perform basic arithmetic. The following command displays "3" in the Output window:

trace(5 - 2);

The less-than operator (<) checks which of two numbers is smaller or determines which of two letters is alphabetically first:

if (3 < 300) {   // Do something... } if ("a" < "z") {   // Do something else... }

The combinations, comparisons, assignments, or other manipulations performed by operators are known as operations. Arithmetic operations are the easiest operations to understand, because they follow basic mathematics: addition (+), subtraction (-), multiplication (*), and division (/). But some operators will be less recognizable to you, because they perform specialized programming tasks. Take the typeof operator, for example. It tells us what kind of data is stored in a variable. So, if we create a variable x, and assign it the value 4, we can then ask the interpreter what datatype x contains, like this:

var x = 4; trace (typeof x);

When this code is executed, Flash displays the word "number" in the Output window. Notice that we provided the typeof operator with a value upon which to operate x but without using parentheses: typeof x. You might therefore wonder whether x is an argument of typeof. In fact, x plays the same role as an argument (it's an ancillary piece of data needed in the computation of the phrase of code), but in the context of an operator, it is officially called an operand. An operand is an item upon which an operator operates. For example, in the expression 4 + 9, the numbers 4 and 9 are operands of the + operator.

Chapter 5 covers ActionScript operators in detail. For now, just remember that operators link together phrases of code in an expression.

1.1.7 Putting It All Together

Let's review what you've learned. Here, again, is line one of our example:

var message = "Hi there, Flash!";

The keyword var tells the interpreter that we're declaring (creating) a new variable. The word message is the name of our variable (a name we've chosen arbitrarily). The equals sign is an operator that assigns the text string ("Hi there, Flash!") to the variable named message. Hence, the text "Hi there, Flash!" becomes the value of message. Finally, the semicolon (;) tells the interpreter that we're finished with our first statement.

Line two is pretty much the same as line one:

var firstName = "your name here";

It assigns the text string you typed in place of your name here to the variable firstName. A semicolon ends our second statement.

We reuse the variables message and firstName in lines three and four:

trace (message); trace ("Hi there, " + firstName + ", nice to meet you.");

The keyword trace tells the interpreter to display some text in the Output window. We pass the text to be displayed as an argument. The opening parenthesis marks the beginning of our argument. The trace( ) command requires one argument, but that argument might be a fairly complex expression. For example, in line four, the argument includes two operations, both of which use the plus operator, joining three operands. The first operation joins its first operand, "Hi there, " to the value of its second operand, firstName. The second operation joins the text ", nice to meet you." to the result of the first operation. The closing parenthesis marks the end of our argument, and the semicolon once again terminates our statement. Technically, parentheses demarcate a list of one or more arguments. If a command requires more than one argument, the arguments are separated by commas (the commas in the preceding example are part of the text, because they are enclosed in quotes, and should not be confused with commas used to separate multiple arguments, as shown later).

Blam! You've written your first ActionScript program. That has a nice ring to it, and it's an important landmark.

     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net