Control Blocks

     

A statement is the " sentence " of coding; that is, it is the smallest unit of code that communicates a complete command to the ActionScript interpreter. There are two basic kinds of statements: standalone statements and control blocks. So far, you've seen standalone statements, such as x = 3 * 7; . A control block is a statement that can contain other statements.

There are two kinds of control blocks: looping (or iterative ) and non-looping. The looping control blocks ( while , do-while , for , and for-in ) repeat the statements they contain until a condition is met. The non-looping control blocks ( if-else , ifFrameLoaded , and with ) execute the statements they contain just once.

Sample movie dropdownmenu.fla on the CD accompanying this book generates a drop-down menu using a for-in loop. Notes are in dropdownmenu.htm.


A typical control block consists of a keyword (reserved word, such as if in the following examples), a parenthesized control construct , and a body consisting of zero or more statements. The keyword defines the type of statement (such as an if statement); the control construct determines under what conditions the body is executed; the body determines what actions the control block performs .

If two or more statements appear in the body, they must be enclosed in curly braces. You can write a statement on multiple lines for readability, without affecting what it does. For instance, these two statements are equivalent:

 if (allDone) quit; if (allDone)     quit; 

So are these two:

 if (allDone) {cleanup(); quit;} if (allDone) {     cleanup();     quit; } 

The do-while , for-in , and if-else statements contain two keywords. In a do-while or if-else statement, the second keyword follows the body. (Note that the "else" in the if-else construction is optional.) In the case of for-in , the second keyword is in the control construct.

Table 20.4, which lists keywords used in statements, shows each of these formats.

The keyword and the control construct together make up the header of the control block.

The following example displays numbers from 0 to 49:

 for (var i:Number = 0; i < 50; i++) {      trace(i); } 

Here, for is the keyword, (i = 0; i < 50; i++) is the control construct, and trace(i); is the single statement in the body. Therefore, for (i = 0; i < 50; i++) is the header.

Table 20.4. The ActionScript Statement Keywords

Keyword(s)

Format

Description

Flow Control

break

break;

Cancel the current loop

loop

call

call( frame );

Execute the script on another frame

call

class ( [*] )

 class  className  { // class definition here } 

Declare a static AS2 class

call

continue

continue;

Restart the current loop

loop

do-while

  do {   statements  } while  (expression);  

Repeat statements while expression is true

loop

none (empty statement)

;

Hold a place for a statement

default

for

 for (  init; test; next  ) {  statements  } 

Repeat statements while test is false

loop

for-in

 for (  property in object  ) {  statements  { 

Enumerate properties of objec t

loop

function

 function  name  (  parameters  ) {  statements  } function  name  (  parameters  ):  Datatype  {  statements  } 

Declare a function

Call

Declare a function with a return type

call

if/else “ if/else

 if (  condition1  ) {  statements  } else if (  condition2  ) {  statements  } else {  statements  } 

Execute statements based on one or more conditions

conditional

ifFrameLoaded

 ifFrameLoaded (  frame  ) {  statements  } 

Execute statements if frame has been loaded (deprecated)

conditional

import ( [*] )

 import  className  ; import  packageName;  

Make an AS2 class or group of classes (package) referencable by class name alone (no path required)

call

return

 return; return  expression  ; 

Exit a function Return a value from a function

call

set

set ( variable, value );

Assign a value to a dynamically named variable

default

switch / case / default

 switch(  expression  ) { case  value  :  block  default :  block  } 

Execute statement(s) starting with block where value matches expression (if no match, execute default )

conditional

try/catch/finally

 try {  statement(s)  If  errorCondition  {     throw new Error (  error  )  }   } catch  (  error  )   {  error handling: block  } finally {  statement(s)   }  

In FP7, execute statement(s) If errorCondition ccurs, execute catch block .With error object /text parameter. With.or without error,execute finally block.

conditional

var

 var  variableName  ; var  variableName:Datatype  ; var  variableName:Datatype  =  expression  ; 

Declare a variable, optional

datatype, and optional value

default

while

 while (  expression  ) {  statements  } 

Repeat statements while expression is true

Loop

with

 with (  objectName  ) {  statements  } 

Execute statements in the context of a given object

Loop


[*] Covered in Chapter 21. Require Flash Player 6 or greater. The class statement has other optional formats.

Understanding Program Flow Control

By default, the ActionScript interpreter executes statements sequentially, from top to bottom. However, most statements can change the default program flow. The exceptions are the empty statement, set , and var , which don't affect program flow.

The three basic types of flow control in ActionScript are call, conditional , and loop .

NOTE

The call paradigm of flow control is represented by function calls, including function calls within classes, and by the deprecated call statement. In this paradigm, the call interrupts the interpreter's sequential processing. The interpreter executes a block of code elsewhere in the program and then returns and continues processing at the point where it left off.


NOTE

System events also execute in a definite order in relation to the Main Timeline and the timelines of any child movie clips. For more on this topic, see timelineExecution.htm on the CD accompanying this book.


Conditional and loop flow control are the focus of the next section.

Making Decisions with Conditionals and switch

When the ActionScript interpreter encounters a conditional statement, it evaluates a condition in the control structure and, if the condition is true, executes the statements in the body.

There are two types of conditional statements: if-else and the deprecated ifFrameLoaded . if-else can be broken down into simple if statements and if-else statements.

The if Statement

The simplest conditional is an if statement. The syntax is straightforward:

 if (  expression  ) {  statement1  ;  statement2  ; } 

If expression resolves to a Boolean true , the statements in the body are executed. Otherwise, they are not executed.

Note that any array, object, or movie clip evaluates to true . Therefore, you can use an if statement to test for the existence (or nonexistence) of an array, object, or movie clip. For instance:

 // if array exists, set variable len to length of array if (myArray) {      len = myArray.length; } 

The if-else Statement

An if-else statement is actually two separate but related statements: An if statement tells the interpreter what to do if the expression is true, and an else statement tells the interpreter what to do if the expression is false. For instance, in the following example, if the array myArray already exists, the program sets the variable newArray to false . If the array does not exist, the program creates the array first and then sets newArray to true .

 if (myArray) {      newArray = false; } else {      myArray = new Array();      newArray = true; } 

"Multiple-Choice" Conditionals

You can test for a number of different conditions sequentially, by using multiple "else-if" clauses. For instance:

 if (day == "Monday") {      trace("is fair of face"); } else if (day == "Tuesday") {      trace("is full of grace"); } else if (day == "Wednesday") {      trace("is full of woe"); } 

To make the last trace action a default, substitute the following for the last three lines:

 } else trace("is full of woe"); 

The switch / case Statement

In the previous example, each conditional statement uses the variable day in an equality test. This type of conditional logic can also be expressed using a switch statement, like this:

 switch (day) {      case "Monday":           trace("is fair of face");           break;      case "Tuesday":           trace("is full of grace");           break;      case "Wednesday":           trace("is full of woe"); } 

The interpreter tests the same expression (in this case, the variable day ) against each of a series of expressions (in this case, the string literals "Monday" , "Tuesday" , and "Wednesday" ). When it finds a match, it starts executing statements, beginning with the statement following the matched value.

If the interpreter does not find a match, it looks for a default statement. For instance, to make the last trace action the default, substitute the following for the last three lines:

 default:           trace("is full of woe"); } 

The default statement does not have to be the last statement in the switch body, though it almost always is.

Unlike the "multiple-choice" conditionals in the previous section, the switch statement uses strict equality ( === ) in comparing values. This means switch does not convert datatypes when making a comparison. To be considered equal, the operands must be of the same datatype to begin with.

Both the test value ( day ) and the case values ( "Monday" , "Tuesday" , and "Wednesday" ) can be any valid expressions, as long as each one resolves to a single value. However, the values are usually just string or numeric literals.

Note the break statement in each case. Each case statement specifies a beginning point for code execution. It does not specify any ending point. The break statements cause the interpreter to exit the switch statement after executing the statements associated with a single case. If multiple cases are executing one after another, you may have omitted break statements.

If a case statement isnt executing as expected, see the "Troubleshooting" section at the end of this chapter, page 535 .


The try/catch/finally Statement
graphics/new_icon.jpg

The try/catch/finally statement, which requires Flash Player 7, provides a standard framework for testing for and responding to errors. It consists of three blocks of code:


  • In the try block, you attempt to do something and then test for an error condition. If an error occurs, you use the throw keyword to generate an error call. The throw call passes an argument, which is often just a text string, but can be any ActionScript object.

  • The catch block automatically receives the call made in the throw block, including the passed parameter. Within the catch block, you respond to the error.

  • The finally block executes whether or not an error occurs.

In the following fully functional example (tryCatch.fla on the CD), the getCustomerInfo() function (line 1) simulates an error condition by returning 1. Within the try block, line 4 tests for an error return (any return to other than 0). The throw statement on line 5 passes a text string, which is "caught" on line 7, in this case just displaying the text string in the Output window.

 1:  function getCustomerInfo() { return (1); } 2:  try { 3:    var returnVal = getCustomerInfo(); 4:    if(returnVal != 0) { 5:      throw new Error("Error getting Customer information."); 6:    } 7:  } catch (e) { 8:    trace(e); // error processing goes here 9:  } 10: finally {trace("finally")}; // "clean-up" or other final actions 

If a function returns specific error codes (say 1, 2, and 3), you can have a switch statement or multiple if statements in the try block, testing for specific error returns and passing a different parameter, depending on which error has occurred.

The ifFrameLoaded Statement

The ifFrameLoaded statement is deprecated (supported for now but not forever), but it is still popular. The ifFrameLoaded statement offers compatibility with Flash 3. The recommended substitute, _framesLoaded , requires at least Flash 4.

The ifFrameLoaded statement is a special case of the if statement, which checks whether a specific frame ( optionally in a specific scene) has loaded yet. It is used to make preloaders for movie clips.

For instance, if you put the following code on the first two frames of a movie clip, the clip loops through the first two frames until frame 60 has loaded. Then it will start playing from frame 5.

 //frame1: ifFrameLoaded (60) {     gotoAndPlay (5); } //frame2: gotoAndPlay (1); 

The recommended substitute for ifFrameLoaded (60) is the framesLoaded property of the movie clip:

 if (_framesLoaded == 60) 

With ifFrameLoaded , you can also include a scene name:

 ifFrameLoaded ("intro", 60) { 

One limitation of ifFrameLoaded is that it does not support an else statement (whereas _framesLoaded does). The two-frame structure uses a two-frame loop to mimic an else clause.

Using Loops to Repeat Actions

The loop statements, while , do-while , for , and for-in , are used to perform repetitive actions. Each repeatedly evaluates a condition and uses the result of the evaluation to decide whether to continue looping through the body. For example, a loop could be used to repetitively check whether a certain amount of time has elapsed, or to repetitively duplicate a movie clip until a certain number of clips has been created.

The four loop statements are closely related. The while and for statements are basically two ways of doing the same thing: Which you use is often a matter of taste. The Flash compiler translates both into while loops in the SWF. And do-while is just a minor variation of while .

The while Statement

The while statement is the basic statement for performing repetitive actions. The format for the while statement is

 while (  expression  ) {  statement1  ;  statement2  ;  statement3  ; } 

The interpreter loops through the statements as long as the expression is true, unless it encounters a break statement, in which case it exits the loop. For instance, the following while loop puts a half-second (500 millisecond) delay into the program. It is based on the fact that elapsed time is the current time (obtained using getTimer() ) minus the initial time:

 initialTime = getTimer(); while (elapsedTime < 500) {      elapsedTime = getTimer() - initialTime; } 

It is common to implement a while statement with a counter ( i in the following example), which is initialized before the while loop and incremented within the while loop, until it reaches the count (500 in this case) defined in the control block:

 var i:Number = 0; while (i < 500) {     i++;      // do something 500 times } 

The do-while Statement

The body of a while loop does not execute even once if the condition is false from the beginning. To make the while loop execute at least once, use the do-while statement. For example:

 do {  statement1  ;  statement2  ;  statement3  ; } while (  expression  ); 

Looping statements present the danger of infinite loops, if expression remains true forever. For an example of an infinite loop, see infiniteLoop.htm and recursion.htm on the CD accompanying this book.


The for Statement

A while loop can have a counter that is initialized and updated. The for statement makes initialization and updating part of the parenthesized control structure. The format of the for statement is as follows:

 for (  initialization; condition; update  ) {  statement1  ;  statement2  ;  statement3  ; } 

For instance, the following is the most recent while shown previously, put into the form of a for loop:

 for (var i:Number = 0; i < 500; i++) {      // do something 500 times } 

Whether you use the while loop or the for loop is a matter of taste. The for loop is more concise . Its structure also reminds you to include the increment. Leaving the increment out of a while loop is a common error that leads to an infinite loop. On the other hand, the while loop allows you to comment the initialization, condition, and increment expressions separately.

The for-in Statement

The for-in statement enumerates or lists the properties of an object. It can be extremely useful for investigating existing objects that you did not define, such as built-in objects or objects associated with components . Its format is as follows:

 for (  variable  in  objectName  ) {  statement1  ;  statement2  ; } 

The variable name in the control structure is an arbitrary name that you pick, such as prop in this example. As the for-in statement loops, it contains the name of each property in succession ( title , author , and language in the example).

 myBook = {  title : "Huckleberry Finn",  author : "Mark Twain",  language : "English"}; //create object, myBook for (prop in myBook) {      trace(prop+" : "+myBook[prop]); } 

This will display, on three lines, title : Huckleberry Finn , author : Mark Twain , language : English .

Note that the variable in the control structure contains the name of the property, not the value of the property. You can easily access the value when you have the name. For instance:

 trace(myBook.title); // "Huckleberry Finn" 

myBook["title"] is another way of expressing myBook.title . In a the example, myBook[prop] is equivalent first to myBook["title"] , then to myBook["author"] , and finally to myBook["language"] .

See "The Object Class," page 572 , "The PrintJob Class," page 600 , and "Other Handy Flash CSS Features," page 611 , in Chapter 21, for more examples that use the for-in statement.




Using Macromedia Studio MX 2004
Special Edition Using Macromedia Studio MX 2004
ISBN: 0789730421
EAN: 2147483647
Year: N/A
Pages: 339

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