Chapter 4. Basic Programming in Flash

CONTENTS
  •  Terminology, Special Characters, and Formatting
  •  Data Types and Variables
  •  Using Variables
  •  Dot Syntax
  •  Summary

Although you don't have to know traditional programming concepts to use ActionScript, they will help you greatly in Flash. If you're experienced in another programming language, this chapter might look familiar to you. Flash's ActionScript language is based on the same standard used by JavaScript (called ECMA-262; see www.ecma.ch). As such, many aspects are similar or identical. This chapter is a good introduction for both experienced programmers as well as those with basic Flash skills. I'll explain some general programming concepts, but with specific attention to how they apply to Flash.

In this chapter, you will:

  • Learn basic programming terms.

  • Recognize built-in script elements.

  • Get an overview of traditional concepts such as variables and data types.

Terminology, Special Characters, and Formatting

The terms and rules in programming are very strict. This can actually be helpful. Unlike in English, where the meaning of a sentence can be ambiguous or vague, in programming there are absolutes. After you fully understand what a "property" is, for example, you never need to wonder what kind of property as you would with the word property in English, which has multiple meanings. Not only do terms in programming have absolute meanings, they're usually closely related to the word's meaning in English. Be careful, however; sometimes your first impression of a term could carry a special meaning to you that is unrelated to the true meaning. Luckily, most terms are very easy to learn.

Events

Everything that happens in Flash is the result of an event that causes a script to execute. Even for such a simple example as the user clicking a button that causes the movie to skip ahead, the instructions (to skip ahead) resulted from the click "mouse event."

There are three types of events in Flash: keyframes, mouse events, and clip events. Notice that these correlate to the three places you can place scripts (keyframes, button instances, and clip instances). If you place a script in a keyframe, the script will execute as soon as Flash reaches the keyframe. In the case of buttons, you must always specify the mouse event to which you want to respond. Similarly, scripts on clip instances need to include a clip event. Figure 4.1 shows the available mouse events and clip events.

Figure 4.1. The mouse events (for buttons) on the top and the clip events (for clips) on the bottom include all the events available in Flash.

graphics/04fig01.gif

I like to think of an event as the wrapper of the scripts that it contains. Consider that you can't just have a stop() Action attached to a button; you must wrap it within a mouse event. I suppose that it makes sense to think the stop() action follows the mouse event. But because you can have several actions follow one event (maybe the button causes both stop() and stopAllSounds() to execute), you need some indication of where the results of an event end. In Flash, the event wrapper starts with an opening curly brace ({) and ends with a closing curly brace (}) sort of like a "script sandwich" with two curly braces for bread and scripts in the middle. Even if that corny analogy doesn't help, you should see that scripts are wrapped inside events. (See Figure 4.2.)

Figure 4.2. Everything between the two curly braces will be performed when the event occurs.

graphics/04fig02.gif

Results of Events

After an event happens, a script is executed. The instructions that Flash follows can range from simple to complex. Let's start by thinking about the results of events in very general terms. First, we'll look at the five types of tasks that happen as the result of an event:

  1. A script can do something that is invisible or unimportant to the user (such as add to a counter that is tracking how many times a button is clicked). Think of this type as laying the groundwork or defining what can happen later.

  2. The script can do something visual (such as change the rotation of a Movie Clip).

  3. The script can trigger another script to execute effectively behaving like a homemade event. Perhaps the script attached to one button causes another script to rotate a Movie Clip. In this way, several buttons can trigger the same "rotate the clip" script and your code can be modularized.

  4. Scripts can "ask" other scripts for information (the part that's said to be "returned") and use the result to do one of the other tasks here. For example, one script could ascertain the current exchange rate from another script and use that information to translate a price from yen to dollars.

  5. Finally, the fifth result of an event is nothing. That might seem odd, but events happen all the time and nothing happens. For example, a linear movie with no buttons will have no response to the mouseDown event (despite the fact that it happened). It's kind of like a tree falling in a deserted forest; that's an event despite whether anyone reacts to it.

Terms

We can't go much further without defining a few terms.

Syntax

Syntax is the way any sentence is organized. In programming, a "sentence of code" is called a statement. The syntax, or the form of your statements, must adhere to strict syntax rules. One simple rule (that works in English, too) is that any parenthetical statement that you start with an opening parenthesis must be followed by a closing parenthesis. If your statement's syntax is incorrect, your code will perform unexpectedly (at best) or not at all (at worst).

graphics/icon02.gif

There are many ways that Flash helps you follow perfect syntax. While you are working in Normal Mode, the Actions panel will all but ensure that your syntax is perfect. Actually, as soon as your statement contains an error, it is highlighted in bright red. An explanatory message appears to guide you along, and often a code hint appears to help you with the proper syntax. Figure 4.3 shows a statement that isn't complete. Remember that even after your syntax is perfected, it doesn't mean your Flash movie will play the way you want it to. The script could still contain logical errors. The first step is to fix the syntax, and then you can ensure that it performs correctly.

Figure 4.3. When you edit your script in Normal Mode, errors are highlighted while you type.

graphics/04fig03.gif

graphics/icon02.gif

Another way that Flash helps you produce perfect syntax is by color-coding certain terms. The Syntax Coloring option in the ActionScript Editor's Preferences dialog box (accessed via the Actions panel's options menu and shown in Figure 4.4) is a great way to learn to type (and spell) terms correctly. Keywords and identifiers (which, for now, you should simply consider as built-in terms of ActionScript) are colored dark blue. Comments (which are ignored by Flash and enable you to write notes to yourself or others reading your code) are colored gray by default. Finally, anything you type between quotation marks is blue. This is particularly useful because you must remember to end any quotations you start (just like parenthetical statements). If you start a quotation, everything that follows will turn gray until you type another quotation mark. You'll find out more about keywords, properties, comments, and strings later in this chapter.

Figure 4.4. The ActionScript Editor's Preferences dialog box enables you to change syntax coloring and fonts, in addition to other settings.

graphics/04fig04.gif

I wanted to mention the Syntax Coloring feature because it's a great way to learn. For example, when you look through someone else's finished code, it's easy to separate the elements that are built-in to Flash (they'll be blue) from the code that the programmer created (left in black). Possibly the most frustrating syntax rule in Flash is that all keywords are case sensitive. For example, goToAndPlay(2) won't turn blue (only gotoAndPlay(2) will). Throughout this book, you'll see many places where syntax is important. Syntax Coloring is just one little helper available to you.

graphics/icon02.gif

Because Syntax Coloring is a preference, you can change any color to meet your needs. (Only the settings are saved with Flash MX, not the file). There's also a new Auto Format feature that helps your code look neat. The Auto Format Options shown in Figure 4.5 are accessible from the Actions panel's options menu. While we're on the subject of "built-in features that help you learn," be sure to study the way code hints work. There's an explanation and table in Chapter 2, "What's New in Flash MX." All these helpers are by no means "cheating" because they help you to become a better programmer.

Figure 4.5. Auto Format Options specify how Flash MX cleans up your code as you type.

graphics/04fig05.gif

Objects, Instances, Instance Names, and Properties

In Flash, there are many types of objects, but the easiest kind to understand are Movie Clip instances. Every Movie Clip you drag from the Library onto the Stage becomes a separate instance. Properties are attributes of objects. In real life, you could compare properties of objects to personal attributes and characteristics of people. People have an eye color property, a height property, a weight property, and so on. If you have two instances on the Stage, they're both based on the original master symbol but each is most likely positioned differently; that is, they'll have different _x and _y properties. Not only can you change properties of individual clip instances while editing, but through scripting you can change each instance's properties at runtime. This is easiest if the clip instance has been given an instance name (via the Properties panel). In pseudo-code, you'd say something like this: Set the _x property of the instance named "box_1." Just remember that the instance name is what matters (not the master name in the Library).

Note

graphics/icon02.gif

By the way, Flash MX enables you to give instance names to several other types of objects, including buttons, text, and video. You'll see this first in Chapter 10, "Keyboard Access and Modifying Onscreen Text," but realize they have a few limits. For example, text must be set to Dynamic or Input. For now, just remember that a Movie Clip is no longer the only object with an instance name.

After you fully understand how to access clip instance properties, it will be easy to understand other objects. In Chapter 7, "The Movie Clip Object," you'll learn how to access and change instance properties. You will use the same techniques in Chapter 9, "Manipulating Strings," Chapter 10, "Keyboard Access and Modifying Onscreen Text," Chapter 11, "Arrays," and Chapter 12, "Objects," to control the sound object, string object, and color object (among others). Finally, in Chapter 13, "Homemade Objects," you'll create your own objects. The reason the Movie Clip is so much easier to understand is that it's an object that you can see and touch. All the other objects are just as real, but you may never grab one with your mouse or see it onscreen. It's sort of like how you can have a picture in your mind. Think of a physical printed photograph as the Movie Clip object you can fold it, frame it, or hang it on the wall. Now, consider a picture in your mind as any of the other objects. Even though there's no physical evidence, you can still manipulate the picture in your mind picture it being folded, framed, and so on.

Statements, Expressions, and Operators

The entire block of text in the Actions panel is a script, where each line is a statement. As mentioned earlier, statements are "sentences of code." It's not so critical if you interchange the terms script and statement. But if a statement of code is like an entire sentence in speech, an expression is like a phrase. In speech, you might use the phrase as slow as molasses. First of all, you'd create an entire sentence (a statement), such as His computer is as slow as molasses. You can see that the expression (or phrase) is only part of the statement.

Expressions in Flash are evaluated. For example, an entire statement might read: halfprice=price/2. The part on the right of the equals sign is an expression and it will be evaluated (that is, a result will be placed in that spot). If it helps, think of evaluated expressions as having "math" done on them. Now, imagine that "as slow as molasses" is an actual speed (say 1 mile-per-hour). If you evaluated the expression, you'd be left with the result "1 MPH." The original sentence would become His computer is 1 MPH. This analogy is beginning to fall apart, but it's a good way to learn about statements and expressions (as well as the standard terms evaluate and result).

Finally, operators perform specific (usually math) operations. They always need at least one number, called an operand, on which to work. For instance, "+" is an operator that performs addition. The "+" addition operator requires two operands to work. Get it? There's the operator (doing the work) and the operands (getting work done on them). The thing to remember is that operators are used within expressions. Therefore, they're evaluated and their results appear in their place. For example, saying whatever=2+2 is the same as saying whatever=4. The expression on the right is evaluated and turns into 4. This might seem simple. Just think of expressions morphing into their results.

Operators are pretty easy to understand when you consider familiar math operators such as multiplication (*), division (/), and subtraction (-). Others aren't so easy to figure out and might even seem arbitrary. For example, one deceptively useful operator uses the percent sign (%), but not to calculate a percent. It's called the modulo operator and results in the remainder of two numbers. 10%2 is evaluated into 0. Ten divided by 2 has 0 for a remainder. This can be useful to determine whether a number is odd or even (or evenly divisible by any other number, for that matter); that is, if the number % 2 is 0, it's an even number because it's evenly divisible by 2. Anyway, I don't recommend memorizing all the operators. We'll use many of them in the Workshop section, especially when we make sliders and the currency exchange calculator. However, after you understand the form that operators create an expression that's evaluated and they always require at least one operand you can learn them gradually.

Actions and Functions

In Flash, "actions" have many meanings. I think it's best to think of actions as Flash-unique commands that execute specific tasks. For example, the stop() action is a command that causes the playback head to stop. The gotoAndPlay ("framelabel") action is another command that jumps to a frame number or label and plays. These actions do things specific to Flash. However, the Actions panel lists many "actions" that are, technically, statements (or elements of statements). Figure 4.6 shows some actions that are really statements. For example, if is a piece of code that creates a statement. You have to specify additional details (such as, "If what?"), but if was around way before Flash and in my book, it's a statement. For the sake of understanding, I'll try to avoid the term "actions" completely.

Figure 4.6. All the "actions" in Flash are actually a mix of statements and Flash-unique commands.

graphics/04fig06.gif

Keep in mind that although the term "actions" is made up, actions behave in a consistent manner. All the actions in Flash are one of two types. They're either specific Flash commands (such as stop, duplicateMovieClip, and play), or they are statements (such as if or break). (Actually, you'll learn in the next chapter that a more common name for many actions is method.) Many actions (of either type) need additional parameters provided for instance, gotoAndPlay() requires a frame label or number. Another consistent attribute of all actions is that they're never evaluated; they do things. Actions have consequences. (To avoid confusion, don't call them "results.") The script you create using actions doesn't morph into a result the way that expressions do. Actions simply "do things." Either they help construct a statement or they do a Flash-unique task.

Although Flash's built-in functions are easy to confuse with actions, they are different in a profound way. A function always returns a value. That is, a built-in function's job is to calculate an answer. Similar to how an expression is evaluated, a function "returns" a value, which, in turn, is placed where the function was called. For example, the function getTimer() returns the total number of milliseconds elapsed since the movie started. It's almost like a "what time is it?" function. But consider if you asked someone, "What time is it?" That person might look at her watch, but unless she "returns" the answer, you might never know what time it is. Similarly, if you just wrote the script getTimer(), it would be meaningless. The getTimer() would turn into a number maybe 10200, but so what? If, however, you wrote elapsedTime=getTimer()/1000 + " seconds", the getTimer() part would turn into 10200 and the expression on the right side of the equation would evaluate as 10.2 seconds.

All the built-in functions behave this way. Consider these real-life activities as actions: drive a car, stop the car, fill the car with gas. Now consider these as functions: getting today's price of gas, determining how many liters fit in a 20-gallon gas tank, determining how many yen are equal to 10 dollars. The functions always result in an answer (which can be used within a bigger calculation). Notice, too, that some functions just provide an answer (such as "getTimer" or "getting today's price of gas"). However, other functions (such as "converting gallons to liters") require additional data to be provided (that is, "How many gallons?"). In these cases, you need to provide a parameter.

In Chapter 8, "Functions," you'll learn all about functions both the built-in functions and homemade functions. For now, just understand that actions are either Flash-unique commands (also called methods) or statements, and that built-in functions always return values. The big difference is that an action can be used by itself, whereas a function is always used within a larger script.

Special Characters and Formatting

As part of the many syntax rules in Flash, certain characters have special meanings. Additionally, the layout or format of your scripts must follow some rules. Parentheses are a perfect example of this point. Any parenthetical statement must start with an opening parenthesis and must always end with a closing parenthesis. The reason this is important is that you can have nested parentheses like this: ((6+2)*3)/2, which results in 12. That's different than 6+((2*3)/2), which results in 9. The innermost expressions are evaluated first, followed by expressions in outer parentheses. The point is that anything you start, you have to finish. For example, ((6+2)*3/2 will cause an error because there's an extra open parenthesis.

There are identical rules for quotation marks ("), brackets ([ and ]), and curly braces ({ and }). Quotation marks are a little different because apostrophes will work the same as quotation marks. This way you can nest quotations in quotations. You can't mix and match, however. For example, all of these are legitimate:

"This is 'cool' "  'Flash version "MX" is More eXemplary than "5"'  "Phillip's dog is named Max"

But these won't work:

"What you "start" you have to "finish""  "Mixing will not work'

It's interesting because in the case of "Phillip's dog ", you might think that the apostrophe would cause problems. It works fine, however. Also, nested quotation marks are different than nested parentheses. You can have two open parentheses in a row, and as long as you eventually close what you open, they will work fine. However, two quotation marks in a row will cause Flash to think that the second one is closing what the first one opened. So, if you have to nest quotations in quotations, you must use quotations for one and apostrophes for the other. (By the way, the curly, or "smart," quotation marks, " and ",won't work in the Actions panel.)

Generally, spaces and return characters (at the end of a line) are ignored by Flash. If you start a parenthetical statement and close it five lines later, there's no problem. Because you can't simply create a new line to represent a new thought, every line of code can be terminated with a semicolon. For example, look at this piece of code:

if (age>18){     voter=1;      draftable=1;  }

Even though we haven't looked at the if statement yet, you can see that the open curly brace is followed (three lines later) by a closing curly brace. Also, there are two separate lines of code, each ending with a semicolon. Actually, the following is also totally legitimate:

if (age>18){voter=1;draftable=1;}

The first example was easier to read. In either case, the semicolon clearly ended individual statements. Occasionally you can be sloppy and, based on context, Flash will figure out what you intended. It's best to deliberately use semicolons to end each line, however.

One of the best character sequences to learn is the double forward slash (//), which creates a comment. Comments are ignored by Flash, so you can write anything you want. You can use comments as notes to yourself (or anyone else who might be viewing your code). The phrase "commenting your code" means that you include all the information necessary to make sense of your code through comments. Also, comments are useful to cause Flash to temporarily ignore part of your code effectively removing the code, but leaving it so that you can restore it easily.

Everything that follows // (on the same line) is ignored. You'll see the commented text turn pink, which makes it very easy to recognize. The following code sample includes comments:

//This button makes the movie stop  on (release) {     stop(); //don't go any further  }

Normally, comments automatically end at the end of a line. (Notice that there's no "closing" comment mark in the code.) However, you can use /* to start a block of comments that will continue until a */ is reached.

/* Comments:      This is a comment.      This is another comment.  */

We'll encounter other special formatting and new terms throughout this book, but this should give you a good start. Now, with the terms and other technical matters out of the way, we can move on to variables and how to use them.

Data Types and Variables

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

Variables' Names and Values

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

String and Number Data Types

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

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

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

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

More About Strings

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

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

graphics/04fig07.gif

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

More About Numbers

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

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

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

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

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

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

myAge="3";  myAge=myAge+1;

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

Other Data Types

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

Primitive Data Types Versus Reference Data Types

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

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

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

Now, consider this example of copying by reference:

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

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

Objects and Arrays

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

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

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

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

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

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

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

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

Using Variables

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

Assigning and Accessing Variables

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

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

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

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

Comparing and Passing Values

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

if (age>17){     canVote=true;  }

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

minimumAge=18;  if (age>minimumAge-1) {     canVote=true;  }

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

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

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

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

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

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

Scope and Variable Collision

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

Note

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

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

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

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

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

Global Variables

graphics/icon02.gif

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

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

Local Variables

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

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

var counter;

or

var counter=0;

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

Dot Syntax

ActionScripting uses what's called dot syntax. You've already seen this in effect throughout this chapter. When we used someClip._y, it could be translated to "someClip's _y property." (Think of the dot as a possessive s.) In this way, the dot separates a clip instance name from its property. If you have clips nested inside of other clips, you can use dots to separate the nested clip names (_root.someClip._y or someClip.subClip._y, for example). You can also use dots to separate clip names from their respective variables. (This fact is probably easiest to learn if you think of variables as custom properties.) Finally, the dot is used to separate a clip name from the method (or action) when you want to apply the method to an individual clip (someClip.gotoAndPlay(2), for example).

The form of dot syntax is interesting because it always reads left to right, from general to specific. In speech, we usually refer to things from specific to general. For example, "The age of the mayor of Portland, Oregon" reads from specific to general. If these were nested clips in Flash, however, it would read the other way: Oregon.Portland.Mayor.age. Depending on whether your target path is relative or absolute, the length might change, but it's always from general to specific. (Chapter 7 discusses relative and absolute paths in greater detail.)

Dot syntax is quite easy to learn. Just remember that you can't name variables or clips with periods in their name. Also, although you're allowed to name clips with spaces (but you shouldn't), you can never name variables with spaces in their names. You might imagine if your clip name were "clip.one," there would be no way to tell whether clip.one._y referred to the _y property of the clip "one" inside the clip "clip" or to the _y property of a clip named "clip.one." By avoiding periods and spaces in clip and variable names, you avoid this issue. Finally, you shouldn't name clips or variables beginning with a numeral. To summarize: Clip instance names and variable names should include no spaces, no periods, and never start with a number.

Summary

This chapter has consolidated practically every component of ActionScript. Naturally, it's more of a starting point rather than the last word. It's fair to say that everything covered will be revisited in much more detail throughout the rest of the book.

Everything was important in this chapter, of course, but you should retain a few concepts in particular. For example, you should be comfortable with all the terms used, even if you don't fully understand their application. You should understand the basic purposes of "events,""properties,""syntax,""statements," and "expressions." The concept of data types is very important, but the good news is that you'll hear more about it later. Regarding variables, if you only grasp that they are a safe yet temporary storage mechanism, you'll be fine.

Just treat this chapter as an overview of the basic programming skills that you're about to develop.

CONTENTS


ActionScripting in MacromediaR FlashT MX
ActionScripting in MacromediaR FlashT MX
ISBN: N/A
EAN: N/A
Year: 2001
Pages: 41

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