Previous Page
Next Page

Recipe 1.9. Performing Actions Conditionally

Problem

You want to perform some action only when a condition is true.

Solution

Use an if or a switch statement.

Discussion

You often need your ActionScript code to make decisions, such as whether to execute a particular action or group of actions. To execute some action under certain circumstances, use one of ActionScript's conditional statements: if, switch, or the ternary conditional operator (? :).

Conditional statements allow you to make logical decisions, and you'll learn from experience which is more appropriate for a given situation. For example, the if statement is most appropriate when you want to tell a Flash movie to do something only when a certain condition is met (e.g., when the condition is true). When you have several possible conditions to test, you can use the switch statement instead. And you can use Flash's ternary conditional operator to perform conditional checking and assignment on a single line.

First let's look at the if statement. Of the conditional statements in ActionScript, the if statement is the most important to understand. In its most basic form, an if statement includes the keyword if followed by the test expression whose truthfulness you want to evaluate to determine which action or actions to execute. The test expression must be in parentheses and the statement(s) to be executed should be within curly braces (the latter is mandatory if there is more than one statement in the statement block).

Here we check whether animalName contains the word "turtle." This might be used to check whether the user answered a quiz question correctly (here, animalName is a variable assumed to contain the user's answer). Note that the double equals sign (==) is used to test whether two items are equal. It should not be confused with the single equals sign (=), which is used to assign a value to an item.

if (animalName == "turtle") {
  // This trace(  ) statement executes only when animalName is equal 
  // to "turtle".
  trace("Yay! 'Turtle' is the correct answer.");
}

Additionally, you can add an else clause to an if statement to perform alternative actions if the condition is false. Note that for the trace( ) command to have any effect, the .swf must be compiled using Debug, and not Run, mode. Make a call to a method named showMessage( ) that displays an appropriate message depending on whether the user got the answer right or wrong:

if (animalName == "turtle") {
  // These statements execute only when animalName is equal 
  // to "turtle".
  showMessage("Yay! 'Turtle' is the correct answer.");
}
else {
  // These statements execute only when animalName is not equal 
  // to "turtle".
  showMessage("Sorry, you got the question wrong.");  
}

For testing purposes, you can create a showMessage( ) method that traces out the string sent to it. In a real-world example, you might want to display this message in a text field, or display it to the user some other way, such as in a dialog box.


You can add an else if clause to an if statement. If the if condition is true, the else if clause is skipped. If the if condition is false, the ActionScript interpreter checks to see if the else if condition is true:

if (animalName == "turtle") {
  // This trace(  ) statement executes only when animalName is equal 
  // to "turtle".
  showMessage ("Yay! 'Turtle' is the correct answer.");
}
else if (animalName == "dove") {
  // This trace(  ) statement executes only when animalName is not 
  // "turtle", but is "dove".
  showMessage ("Sorry, a dove is a bird, not a reptile.");
}

What if the preceding example was written as two separate if statements (one to check if animalName is "turtle" and another to check if it is "dove")? The example would work as intended, but it would be less efficient. Using the else if statement guarantees that if animalName is "turtle"; we don't bother checking if it is also equal to "dove."

If your two conditions are mutually exclusive, use an else if clause to check the second condition. If your two conditions are not mutually exclusive, and you want to perform both statement blocks when both conditions are met, use two separate if statements.


When you use an if statement with both else if and else clauses, the else clause must be the last clause in the statement. The final else clause is convenient as a catchall; it's where you can put statements that take the appropriate action if none of the other conditions are met.

if (animalName == "turtle") {
  // This trace(  ) statement executes only when animalName is equal 
  // to "turtle".
  showMessage ("Yay! 'Turtle' is the correct answer.");
}
else if (animalName == "dove") {
   // This statement executes only when animalName is not 
   // "turtle", but is "dove".
  showMessage ("Sorry, a dove is a bird, not a reptile.");
}
else {
  // This statement executes only when animalName is neither 
  // "turtle" nor "dove".
  showMessage ("Sorry, try again.");
}

You can also include more than one else if clause in an if statement. However, in that case, you should most likely use a switch statement instead; generally, switch statements are more legible and succinct than the comparable if statement. Where performance is critical, some ActionScripters prefer to use if statements, which allow somewhat greater control for optimization purposes.

A switch statement is composed of three parts:



The switch keyword

Every switch statement must begin with the switch keyword.



Test expression

An expression, enclosed in parentheses, whose value you want to test to determine which action or actions to execute.



The switch statement body

The statement body, enclosed in curly braces, is composed of cases. Each case is made up of the following parts:



The case or default keyword

A case must begin with a case keyword. The exception is the default case (analogous to an else clause in an if statement), which uses the default keyword.



Case expression

An expression, whose value is to be compared to the switch statement's test expression. If the two values are equal, the code in the case body is executed. The default case (the case that uses the default keyword) does not need a case expression.



Case body

One or more statements, usually ending in a break statement, to be performed if that case is TRue.

The switch keyword is always followed by the test expression in parentheses. Then the switch statement body is enclosed in curly braces. There can be one or more case statements within the switch statement body. Each case (other than the default case) starts with the case keyword followed by the case expression and a colon. The default case (if one is included) starts with the default keyword followed by a colon. Therefore, the general form of a switch statement is:

switch (testExpression) {
  case caseExpression:
    // case body
  case caseExpression:
    // case body
  default:
    // case body
}

Note that once a case tests TRue, all the remaining actions in all subsequent cases within the switch statement body also execute. This example is most likely not what the programmer intended.


Here is an example:

var animalName:String = "dove";

/* In the following switch statement, the first trace(  ) statement 
   does not execute because animalName is not equal to "turtle". 
   But both the second and third trace(  ) statements execute, 
   because once the "dove" case tests true, all subsequent code 
   is executed.
*/
switch (animalName) {
  case "turtle":
    trace("Yay! 'Turtle' is the correct answer.");
  case "dove":
    trace("Sorry, a dove is a bird, not a reptile.");
  default:
    trace("Sorry, try again.");
}

Normally, you should use break statements at the end of each case body to exit the switch statement after executing the actions under the matching case.

The break statement terminates the current switch statement, preventing statements in subsequent case bodies from being erroneously executed.


You don't need to add a break statement to the end of the last case or default clause, since it is the end of the switch statement anyway.

var animalName:String = "dove";

// Now, only the second trace(  ) statement executes.
switch (animalName) {
  case "turtle":
    trace("Yay! 'Turtle' is the correct answer.");
    break;
  case "dove":
    trace("Sorry, a dove is a bird, not a reptile.");
    break;
  default:
    trace("Sorry, try again.");
}

The switch statement is especially useful when you want to perform the same action for one of several matching possibilities. Simply list multiple case expressions one after the other. For example:

switch (animalName) {
  case "turtle":
  case "alligator":
  case "iguana":
    trace("Yay! You named a reptile.");
    break;
  case "dove":
  case "pigeon":
  case "cardinal":
    trace("Sorry, you specified a bird, not a reptile.");
    break;
  default:
    trace("Sorry, try again.");
}

ActionScript also supports the ternary conditional operator (? :), which allows you to perform a conditional test and an assignment statement on a single line. A ternary operator requires three operands, as opposed to the one or two operands required by unary and binary operators. The first operand of the conditional operator is a conditional expression that evaluates to either true or false. The second operand is the value to assign to the variable if the condition is true, and the third operand is the value to assign if the condition is false.

               varName = (conditional expression) ? valueIfTrue : valueIfFalse;


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)