Creating Expressions in ActionScript


You can write expressions either by manually typing in the primary option fields of ActionScript commands, or by dragging and dropping actions from action booklets in the Actions panel. There are no scripting wizards in Flash; Flash 8 does not automatically script anything for you (not counting components, which already include many lines of code to perform specific tasks for you). However, Flash provides you with booklets of operators, objects, and functions available in the ActionScript language.

Operators

Operators perform combinations, mathematical equations, and value comparisons. See Table 24-1 for a list of common operators in the ActionScript language.

Table 24-1: ActionScript Operators

Flash 5+

Flash 4

Description

+

+

Adds number values (all player versions) and joins, or concatenates, strings in Flash Player 5 and later.

-

-

Subtracts number values.

*

*

Multiplies number values.

/

/

Divides number values.

=

=

Equals; used for assignment of variables, properties, methods, and so on in Flash Player 4 or later.

==

=

Numeric operator: Is equal to; used for comparison in if/else...else if conditions.

!=

<>

Numeric operator: Does not equal.

<

<

Less than.

>

>

Greater than.

<=

<=

Less than or equal to.

>=

>=

Greater than or equal to.

()

()

Groups operations together, as in x = (x+y) * 3;.

""

""

Indicates that the enclosed value should be interpreted as a string, not as an expression.

==

eq

String operator: Is equal to; for example, if (name == "derek") or if (name eq "derek").

=== (F6+)

N/A

Strict equality operator; both of the compared values must be the same data type and value. This operator is compatible only with Flash Player 6 or higher.

!=

ne

String operator: Is not equal to.

!== (F6+)

N/A

Strict inequality operator; both of the compared values must have different values and data types. This operator is compatible only with Flash Player 6 or higher.

<

lt

Alphabetically before; if the strings compared have multiple characters, the first character determines the alphabetical position.

>

gt

Alphabetically after.

<=

le

Alphabetically before or the same as.

>=

ge

Alphabetically after or the same as.

+

add

Joins two strings together or adds a string to a variable.

&&

and

Logical comparison; requires that two or more conditions be met in a single comparison.

||

or

Logical comparison; requires that one of two or more conditions be met in a single comparison.

!

not

Logical comparison; requires that the opposite of a condition be met in a single comparison.

General and Numeric Operators

These operators are used for common mathematical operations of adding, subtracting, multiplying, and dividing. You can also use these operators to compare numeric values, such as > or <.

 if (results > 1) name = "Robert"; _root["name_" + i] = "Ezra"; 

String Operators

To join two String values to another in Flash Player 5 or higher movies, use the + string operator, such as:

 var fullName = firstName + " "+ lastName; 

The Flash Player 4-specific operator add joins one value with another value or expression. If you want to concatenate two variables to create a new variable, use the add string operator. Again, this syntax should be used only for Flash Player 4 or FlashLite 1.0/1.1 movies.

 set ("fullName", firstName add " "add lastName); 

Logical Operators

These operators join several expressions to create conditions. We discuss these further in the "Checking conditions: if else actions" section of this chapter.

 // Flash Player 5 and later syntax below if (results > 1 && newResults < 10){    // do something... } // Flash Player 4 syntax below if (results > 1 and newResults < 10){    // do something... } 

Table 24-1 describes the ActionScript operators available in Flash 4 and higher syntax.

Checking Conditions: if else Actions

Conditions lie at the heart of logic. To create an intelligent machine (or application), you need to create a testing mechanism. This mechanism (called a conditional) needs to operate on rather simple terms as well. Remember the true/false tests you took in grade school? if/else statements work on a similar principle: If the condition is true, execute a set of actions. If the condition is false, disregard the enclosed actions and continue to the next condition or action.

You can simply create isolated if statements that do not employ else (or else if) statements. Solitary if statements are simply ignored if the condition is false. else statements are used as a default measure in case the tested condition proves false. else if statements continue to test conditions if the previous if (or else if) was false. Refer to the following examples for more insight.

  • Basic if statement. The code between the curly braces is ignored if the condition is false.

     if (condition is true){      then execute this code } 

  • Extended if...else if...else statement. If the first condition is true, the code immediately after the first condition is executed and the remaining else if and else statements are disregarded. However, if the first condition is not true, the second condition is tested. If the second condition is true, its code executes and all other statements in the if group are ignored. If all conditions prove false, the code between the curly braces of the final else is executed:

     if ( first condition is true){      then execute this code } else if (second condition is true){      then execute this code } else {      otherwise, execute this code } 

In production, you could have an if/else structure that assigned the value of one variable based on the value of another, such as:

 if (x == 1){    name = "Margaret"; } else if (x == 2){    name = "Michael"; } else {    name = "none"; } 

Caution 

Do not use a single = sign in a condition, as this actually sets the variable's value. For example, if you wrote if (x = 1){}, ActionScript actually sets x=1, and does not check whether x's value is equal to 1. Moreover, the condition always evaluates to true. In our experience, many beginners make this common mistake in their ActionScript code. We can't emphasize enough the importance of making sure you use an == operator in if and else if expressions for "is equal to" comparisons.

You can add an if statement in ActionScript by choosing the if action from the plus (+) button in the toolbar of the Actions panel, or by selecting it from the Statements ð Conditions/Loops booklet. Between the parentheses of the if() statement, shown as the term condition in the code hint, enter the expression that identifies what circumstance must exist for the actions in your conditional to be executed. Remember that, in your expression, literal strings must be quoted, and the == operator must be used for string or numeric comparisons. To add an else clause, position the text cursor after the closing curly brace (}) of the if() statement, and then double-click the else or else if action in the Statements ð Conditions/Loops booklet.

Note 

There's nothing stopping you from just typing the actions directly in the Script pane as well. Use the booklets as a guide at first, to learn about the choices you have available.

Tip 

If you find it confusing when to use parentheses or curly braces ({}) with your code, use the shortcut keys to create code blocks such as if statements. With your cursor active in the Script pane, type Esc+I+F in sequence to create the if statement with the proper set of parentheses and curly braces.

You can join two conditions using logical compound operators such as and (&&), or (||), or not (!), as in:

 if (results >1 && newResults < 10){      gotoAndPlay ("end"); } else if (results > 1 ! newResults < 10) {      gotoAndPlay ("try_again"); } 

In this sample code, the first if statement has two expressions — both need to be true in order for the gotoAndPlay("end"); code to execute. If both are not true, the else if condition executes. If the first condition is true and the second condition is not true, the gotoAndPlay("try_again"); code executes. If neither the if nor the else if condition is true, then no code is executed.

We'll take a look at a step-by-step example of if statements in the exercise at the end of this chapter.

Branching Conditions with Switch() and Case

In ActionScript, you can also use switch() and case statements. switch() and case can replace extended if and else if actions. Instead of declaring a true/false expression (as with if statements), switch() uses an expression that can return any value — you are not limited to true and false conditions with switch(). In pseudo-code, a switch() code structure looks like this:

 test a value    if the value equals this expression       then execute this code    if the value equals this expression       then execute this code    if none of the expressions match the value       then execute this code end test 

In the previous code example, one or more if statements (called case clauses) can execute. Meaning, the tested value can execute more than one segment of code nested within the clauses. You could translate the previous pseudo-code into the following ActionScript code:

 var currentFrame = _root._currentframe; switch(currentFrame){    case 10:       helpBox.gotoAndStop("products");    case 20:       helpBox.gotoAndStop("services");    case 30:       helpBox.gotoAndStop("contact");    default:       helpBox.gotoAndStop("error"); } 

In the previous code example, although it's only possible for currentFrame to equal one value, the default clause will also execute — regardless of the value of currentFrame. However, you may not want to execute the default clause (or multiple case clauses). In this situation, you need to use the break action to "escape" the switch() action. The break action prevents subsequent clauses from being evaluated.

In the following code, only one clause can execute:

 var currentFrame = _root._currentframe; switch(currentFrame){    case 10:       helpBox.gotoAndStop("products");       break;    case 20:       helpBox.gotoAndStop("services");       break;    case 30:       helpBox.gotoAndStop("contact");       break;    default:       helpBox.gotoAndStop("error"); } 

You can use switch() actions for many other situations. If you wanted to make a card game in Flash, you could use a switch() expression to pick a card suit based on a random number:

 1.  var suitNum = Math.round(Math.random()*3); 2.  switch(suitNum){ 3.     case 0: 4.        suit = "diamonds"; 5.        break; 6.     case 1: 7.        suit = "spades"; 8.        break; 9.     case 2: 10.       suit = "hearts"; 11.       break; 12.    case 3: 13.       suit = "clubs"; 14.       break; 15. } 16. cardFace.gotoAndStop(suit); 

In this code, a random number is picked (line 1) and used as an expression in the switch() action (line 2). The random number (represented as a variable named suitNum) will then be matched to a case clause. The matching clause will set a variable named suit to equal a specific card suit and exit the switch() action (lines 3 through 15). A Movie Clip instance named cardFace will go to and stop on a frame named after one of the card suits (line 16).

Tip 

In a working example of a card game, the switch() code for the suit matching would occur within a function. We discuss functions in Chapter 26, "Using Functions and Arrays."

Note 

The switch(), case, and default actions can be used in Flash Player 4 or higher movies. Even though the switch() syntax was only introduced in Flash MX/Flash Player 6, the ActionScript will be compiled to be compatible with Flash Player 4 or 5 if you choose these versions in the Version menu of the Publish Settings' Flash tab.

Loops

A loop is a container for a statement or series of statements repeated as long as a specified condition exists. A basic loop has three parts: the condition, the list of statements to be repeated, and a counter update. There are four types of loops in ActionScript:

  • while

  • do ... while

  • for

  • for ... in

Each of these loop types has a specific use. Depending on the repetitive actions you wish to loop, you need to decide how best to accommodate your code with loop actions.

Caution 

These types of code-based loops do not update the contents of the stage with each pass of a loop execution. If you want to automate changes over time on the stage through code, you'll need to use an onEnterFrame() event handler or a setInterval() function. You learn more about these types of actions in Chapter 25, "Controlling Movie Clips," and Chapter 31, "Creating a Game in Flash."

While (condition) { actions }

In this loop type, the condition of the loop is evaluated first, and, if it is true, the actions within the curly braces are executed. The actions will loop indefinitely (causing a script error) unless there is a way out of the loop — a counter update. A counter update will increment (or decrement) the variable used in the while condition. Here you see a breakdown of a typical while loop. Note that a variable used in the condition is usually set just before the while action is executed.

 var count = 1; // Initial variable while (count <= 10){ // Condition   _root["clip_" + count]._xscale = 100/count; // Statements to be repeated   count = count + 1; // Counter update }   // Termination of loop 

In this example, a variable named count starts with a value of 1. The first time the while action executes, count's value is less than (or equal to) 10. Therefore, the actions within the curly braces are executed. The first action in the loop uses the count value to form the name of a Movie Clip instance, clip_1, and alter its X Scale property by a value of 100/1 (which is equal to 100). Then the count variable is incremented by 1, giving it a new value of 2. The while condition is then reevaluated.

The second time the while action is executed, count's value, 2, is still less than (or equal to) 10. Therefore, the actions within the curly braces are executed again. This time, however, the first action in the loop will address the clip_2 instance's X Scale property, and make that property's value 50 (100/2 = 50). Then, count will be incremented by 1, giving it a new value of 3. Again, the while condition is reevaluated.

The while condition will continue to execute its nested actions until count exceeds a value of 10. Therefore, clip_1 through clip_10 will show a decrease in X Scale.

do { actions } while (condition);

This type of loop is very similar to the while loop we discussed previously, with one important exception: The actions in the do{} nesting are always executed at least once. In a do ... while loop, the condition is evaluated after the actions in the loop are executed. If the while condition is true, the actions in the do{} nesting will be executed again. If the while condition is false, the loop will no longer execute.

 count = 1; // Initial variable do{ // do loop   _root["clip_" + count]._xscale = 100/count; // Statements to be repeated   count = count + 1; // Counter update } while (count <= 1); // Condition 

In this example, the actions within the do{} nesting will execute automatically without checking any condition. Therefore, the X Scale of clip_1 will be set to 100, and the count value will increase by 1, giving it a new value of 2. After the actions execute once, the condition is checked. Because the value of count is not less than (or equal to) 1, the loop does not continue to execute.

for (initialize; condition; next) { actions }

The for loop is a supercondensed while loop. Instead of assigning, checking, and reassigning a variable action in three different actions, a for loop enables you to define, check, and reassign the value of a counter variable.

 for(i = 1; i <= 10; i++){ // Initial variable value, condition, and update   _root["clip_" + i]._xscale = 100/i; // Statements to be repeated }  // Termination of loop 

This for loop does exactly the same thing as the while loop example we used earlier. When the loop is started, the variable i is given a starting value of 1. A condition for the loop is specified next, i<=10. In this case, we want the loop to repeat the nested actions until the value of i exceeds 10. The third parameter of the for loop, i++, indicates that i's value should be increased by 1 with each pass of the loop. Note that this parameter can use ++ (to increase by 1) or -- (to decrease by 1) operators. You can also use expressions such as i = i*2 for the update.

for (variableIterant in object) { actions }

The final type of loop, for ... in, is the most complex looping mechanism. A for...in loop does not need a condition statement. Rather, this loop works with a find-and-replace keyword mechanism. Basically, a variableIterant is declared, which is simply a placeholder for a property or position index within an object or array, respectively. For every occurrence of the variableIterant, the actions within the for...in{} nesting will be executed. The for...in loop can only be used with objects and arrays, and even then, not all properties of this element can be enumerated.

 for(name in _root){ // Placeholder and object   if(_root[name] instanceof MovieClip){ // Check the data type of the object      _root[name]._xscale = 50; // Statements to be repeated   } // end if statement } // Termination of loop 

In the preceding code example, the term name is used to designate a property of the _root timeline. In this case, we want to change all Movie Clip instances on the Main Timeline to a 50 percent X Scale value. We don't need to specify the actual target paths of each individual instance — the for...in loop will search for all instances on the Main Timeline, apply the change, and exit the loop.

Although this might look a bit confusing, it can be more helpful than you can imagine. Have you ever had a bunch of nested Movie Clip instances that all needed to play at the same time? In Flash 4, you would have had to use several tellTarget(){} actions, each one specifying the target path. You could use a while loop to shorten the lengthy code, but, even still, you would need to list the specific parts of the each Movie Clip path, as in:

 count = 1; while(count <= 10){      path = eval("_root.clip_" + count);      tellTarget(path){           play();      }      count++; } 

In Flash 4, the preceding code block would tell clip_1 through clip_10 to start playing. But what if you didn't know (or care to remember) all the paths to several differently named Movie Clip instances? For example, if you had a Movie Clip instance named nestAnim with several nested Movie Clip instances with different names (for example, squareAnim, triangleAnim, and circleAnim), you would have to specifically name these instances as targets. In Flash Player 5 or higher, the for . . . in loop lets you control any and all nested Movie Clip instances simultaneously:

 for(name in nestAnim){      nestAnim[name].play(); } 

With just three lines of code, all Movie Clip instances in the nestAnim Movie Clip instance will start to play. How? Remember that the variableIterant name is simply a placeholder for a property of the nestAnim Movie Clip object. The for ... in loop will find every occurrence of an instance inside of nestAnim. And the word name has no significance. You could use a variableIterant myName, and everything would still work fine. Think of the variableIterant as a wildcard in file searches or directory listings in MS-DOS or UNIX:

 nestAnim[*].play(); 

Although this syntax won't work with ActionScript, it does illustrate the processing of a for ... in loop. Everything and anything that is playable on the nestAnim timeline will play.

On the CD-ROM 

Check out the mcPlay.fla and forInLoop.fla files, located in the ch24 folder of the CD-ROM that accompanies this book.

Break

The break action is not a type of loop — it is an action that enables you to quickly exit a loop if a subordinate condition exists. Suppose you wanted to loop an action that hides, at most, clip_1 through clip_10 (out of a possible 20 Movie Clip instances), but you want to have a variable control the overall limit of the loop, as upperLimit does in the following code block. upperLimit's value could change at different parts of the presentation, but at no point do you want to hide more than clip_1 through clip_10. You could use a break action in a nested if action to catch this:

 var count = 1; while(count <= upperLimit){    if(count > 10){       break;    }    _root["clip_" + count]._visible = false;    count++; } 

Tip 

You can use break statements to catch errors in your loops (such as during a debug process). However, you may want to check out Flash's breakpoint feature in the Actions and Debugger panels. For more information on this feature, read Chapter 32, "Managing and Troubleshooting Flash Movies."

Continue

Like the break action, continue enables you to exit the execution of actions within a loop. However, a continue action won't exit the loop action. It simply restarts the loop (and continues evaluating the current condition). Usually, you will place a continue action with an if nest — otherwise, it will always interrupt the actions within the loop action. For example, if you wanted to omit a particular value from going through the loop actions, you could use the continue action to bypass that value. In the following code block, we hide clip_1 through clip_10, except for clip_5:

 count = 1; while(count <= 10){   if(count == 5){     count++;     continue;   }   _root["clip_" + count]._visible = false;   count++; } 

Adding a Loop to Your Actions List

To create a loop, add one of the loop-type actions in the Actions panel, using the plus (+) button in the toolbar of the panel (or selecting it from the Statements ð Conditions/Loops booklet). With code hints enabled, replace the condition code hint term with an expression that describes the conditions under which the loop should continue repeating. Before the end of the loop, be sure to update whatever the loop relies on in order to continue, usually a counter. If you forget to update a counter, you will be stuck forever in the loop, and Flash will imperiously stop the script from continuing.

Loops in ActionScript are not appropriate for running background processes that listen for conditions to become true elsewhere in the movie. While a loop is in progress, the screen is not updated and no mouse events are captured, so most Flash actions are effectively not executable from within a loop. Loop actions are best suited to abstract operations such as string handling (for example, to check each letter of a word to see whether it contains an @ symbol) and dynamic variable assignment.

You should create loops to execute repetitive actions over time, which affect tangible objects in the movie, as repeating frames in Movie Clips. To create a permanently running process, make a Movie Clip with two keyframes. On the first frame, call the subroutine or add the statements that you want to execute; on the second frame use a gotoAndPlay(1); action to return to the first frame. Alternatively, you can use the onClipEvent(enterFrame), onEnterFrame() handler, or setInterval() function to execute repetitive actions.

Properties

Properties are characteristics (such as width and height) of movies and Movie Clips that can be retrieved and set. You can use variables to store the current value of a given property, such as:

 var xPos = _root._xmouse; 

which stores the current X position of the mouse pointer (relative to the Stage coordinates of the Main Timeline) in the variable xPos.

Built-In Functions

ActionScript contains a number of native programming commands known as functions. Among others, these functions include getTimer(), getVersion(), parseFloat(), parseInt(), escape(), and unescape(). It's beyond the scope of this chapter (and this book) to discuss the practical use of every new function and ActionScript element in Flash 8. We do, however, discuss many built-in functions throughout this part of the book.

Cross-Reference 

Because ActionScript has expanded so much over recent versions of the Flash authoring tool, Robert Reinhardt and Joey Lott created a companion book series on Flash ActionScript to specifically address all the terms of the ActionScript language.

Creating and Calling Subroutines

Whether they're called functions, subroutines, or methods, most programming languages provide a mechanism for programmers to create self-contained code modules that can be executed from anywhere in a program. ActionScript supports subroutines by using the ActionScript function constructor. You can create functions on any timeline, and, just like Movie Clip instances, functions have absolute or relative paths that must be used to invoke them. For example, if you have the following function on a Movie Clip named functions_mc, located on the Main Timeline:

 function makeDuplicate(target, limit){    for(var i=1; i<=limit; i++){      _root[target].duplicateMovieClip(target + "_" + i, i);    } } 

then to invoke it from another timeline, you would execute it as follows:

 _root.functions_mc.makeDuplicate("clip",5); 

Executing it creates five duplicates of the Movie Clip instance named clip, naming the duplicates clip_1, clip_2, clip_3, clip_4, and clip_5.

image from book
Subroutines in Flash Player 4 or Flash Lite 1.0/1.1 Movies

To create a subroutine in Flash Player 4 or Flash Lite 1.0/1.1 movies, first attach an action or series of actions to a keyframe, preferably a keyframe that is never played on the timeline. Next, give that keyframe a label. That's it: you have a subroutine. To call your subroutine from any other keyframe or button, simply add a call() action, and then enter the name of the frame containing the subroutine as the parameter of the action. Use the following syntax: Start with the target path to the timeline on which the subroutine keyframe resides, enter a colon (:), and then enter the subroutine name (for example, call ("/bouncingball:getRandom")). When you call a subroutine, all the actions on the specified keyframe are executed. The subroutine must be present on the movie timeline (either as a keyframe or an embedded Movie Clip instance) for it to work.

Subroutines in Flash Player 4 movies do not accept passed parameters, nor do they return any values. To simulate passing and receiving variable values, set the necessary variable values in the action list that calls the subroutine before the frame is called, and then have the subroutine set other variables that can be retrieved afterward by any other actions.

image from book




Macromedia Flash 8 Bible
Macromedia Flash8 Bible
ISBN: 0471746762
EAN: 2147483647
Year: 2006
Pages: 395

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