Controlling a Script s Flow


Controlling a Script's Flow

Typically, actions in your scripts execute consecutively, from beginning to enda sequence that represents your script's flow. Using conditional logic, you can control this flow by scripting specific actions to execute only when specific conditions are met or exist in your movie. By implementing conditional logic in your scripts, you give your movie the capability to make decisions and take action based on various conditions that you set, and your movie takes on more dimensions as a result. You'll use the conditional statements or phrases described in this lesson to implement conditional logic in your scripts.

if/else Statements

At the heart of conditional logic is the simple if/else statement. Here's an example:

  if(moneySaved > 500) {     buyStuff();   }   // next line of actions


The buyStuff() function is called only if the variable moneySaved has a value greater than 500. If moneySaved is equal to or less than 500, the buyStuff() function call is ignored and actions immediately below the if statement are executed.

At its core, a conditional statement looks at a circumstance (placed within parentheses) and determines whether that circumstance is true or false. If the circumstance is true, actions within the statement are executed; if the circumstance is false, the actions are ignored. When you create an if statement, you essentially state the following:

   if(true) {      // do this    }


The data you place within parentheses represents the condition to be analyzed. The data within the curly braces ({}) represents the actions to be taken if the condition exists. If the curly braces are left out, only the next line will be executed if the condition is true. For example:

   if(true)      // do this    // additional actions


As in real life, sometimes an if statement needs to analyze multiple conditions before taking a single action or set of actions. For example:

  if(moneySaved > 500 && billsPaid == true) {     buyStuff();   }


The AND operator (&&) has been added to the statement so that now the buyStuff() function is called only if moneySaved is more than 500 and billsPaid has a value of true. If either condition is false, buyStuff() will not be called.

Using the OR operator (||) allows you to take a slightly different approach:

  if(moneySaved > 500 || wonLottery == true) {     buyStuff();   }


The buyStuff() function is called if either moneySaved has a value greater than 500 or wonLottery has a value of true. Both conditions need not be true for the buyStuff() function to be called, as was the case when using the AND operator (&&) in the earlier example.

You can mix the AND and OR operators to create sophisticated conditional statements like this one:

   if((moneySaved > 500 && billsPaid == true) || wonLottery == true) {      buyStuff();    }


In this script, the buyStuff() function is called only if moneySaved is more than 500 and billsPaid has a value of true, or wonLottery has a value of true. We wrapped the first condition in parenthesis to ensure it was evaluated first.

For Boolean (true/false) variables, you can make expressions more compact like this:

  if((moneySaved > 500 && billsPaid) || wonLottery) {     buyStuff();   }


You can also check for false values with the following expression:

  if(!billsPaid) {     payBills();   }


The payBills() function is called if the billsPaid variable is false.

The following table shows a list of the common operators (known as comparison operators because they're used to compare values) used in conditional logic, with brief descriptions and examples of how they're used.

Operator

Description

Example

Execute the function if...

==

Equality

if(name == "Derek")

name has a value of "Derek"

!=

Inequality

if(name != "Derek")

name has a value other than"Derek"

<

Less than

if(age < 30)

age has a value less than 30

>

Greater than

if(age > 30)

age has a value greater than 30

<=

Less than or equal to

if(age <= 30)

age has a value less than or equal to 30

>=

Greater than or equal to

if(age >= 30)

age has a value greater than or equal to 30

&&

Logical AND

if(day == "Friday"&& pmTime > 5)

day has a value of "Friday" and pmTime has a value greater than 5

||

Logical OR

if(day == "Friday" || day == "Saturday")

day has a value of "Saturday" or "Sunday"


A common mistake when checking equality is to insert a single equals sign (=) where a double equals sign (==) belongs. Use a single equals sign to assign a value (for example, money = 300). Use a double equals sign to check for equality: money == 300 does not assign a value of 300 to money. Rather, it asks whether money has a value of 300.

Note

Although number comparisons are straightforwardafter all, most of us understand that 50 is less than 100text-value comparisons are less obvious. Derek doesn't equal derek even if the same letters are used. With string values, A has a lower value than Z, and lowercase letters have greater values than uppercase letters. Thus, if A has a value of 1, z has a value of 52 (ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz).


if/else if Statements

An if/else if statement is similar to the basic if statement except that it enables your script to react to multiple conditions. Here's an example:

   if(money > 500) {      buyTV("35 inch");    }else if(money > 300) {      buyTV("27 inch");    }    //next line of actions


This script executes various actions depending on the value of money. If money has a value greater than 500, buy the 35-inch TV. If money has a value less than 500, this part of the script is ignored, and the next condition is examined. The next condition says that if money has a value greater than 300, buy the 27-inch TV. Thus, if money has a value of 450 when this script is executed, the first part of the statement is ignored (because 450 is not greater than 500), and the second part of the statement is executed (because a value of 450 is greater than 300). If money has a value less than 300, both parts of this statement are ignored.

You can create several lines of if/else if statements that react to dozens of conditions.

if/else Statements

An if/else statement allows your script to take action if no conditions in the statement are proven true. Consider this the fail-safe part of the statement.

  if(money > 500) {     buyTV("35 inch");   }else if(money > 300) {     buyTV("27 inch");   }else {     workOvertime();   }   //next line of actions


In this script, if money doesn't have a value of at least 300, neither of the conditions analyzed is true; as a result, neither of the actions that follow the conditions will be executed. Instead, the actions following the else part of the statement are executedit's a bit like saying this:

   If this is true      Do this    otherwise, if this is true      Do this    otherwise, if none of the conditions above are true      Do this


switch/case Statements

A switch/case statement can be used to more efficiently replace some larger if/else if statements. It can be used if you want a script to take a specific set of actions when an exact value exists. For example:

   switch(favoriteBand) {      case "Beatles":        gotoAndPlay("Beatles");        break;      case "U2":        gotoAndPlay("U2");        break;      default:        gotoAndPlay("Mozart");     }


A single expression in parentheses (usually a variable) is evaluated once. The value of the expression is compared with the values for each case in the structure. If a match exists, the block of code associated with that case is executed. If no match is found, the default statement at the end is executed. Each case can check string values (as shown in the example), numeric values, and Boolean values of true and false. We use the break command in each case to prevent the code from automatically running into the next case if a match has already been found. Removing the break statements allows for a way to handle OR conditions. For example:

  switch(favoriteBand) {     case "Beatles":     case "U2":       gotoAndPlay("Rock");       break;     case "Tim McGraw":     case "Faith Hill":       gotoAndPlay("County");       break;     default:       gotoAndPlay("Classical");   }


The preceding statement says, if favorateBand equals "Beatles" or "U2", go to the frame labeled "Rock"; if favoriteBand equals "Tim McGraw" or "Faith Hill", go to the frame labeled "County"; if neither condition is met go to the frame labeled "Classical".

Because the expression in the switch statement is only evaluated once, there can be a significant performance improvement over a regular if/else if statement that requires each condition to be evaluated.

Conditional Operator

The conditional (ternary) operator (?:) is a shorthand version of an if/else statement. Here's an example:

  var myMood:String = (money > 1000000) ? "Happy" : "Sad";


If the condition within the parentheses evaluates to true, the first expression ("Happy") is set as the value of myMood. If the condition evaluates to false, the second expression ("Sad") is used. This single line of ActionScript accomplishes the same thing as the following code:

  if(money > 1000000) {     myMood = "Happy";   }else {     myMood = "Sad";   }





Macromedia Flash 8 ActionScript Training from the Source
Macromedia Flash 8 ActionScript: Training from the Source
ISBN: 0321336194
EAN: 2147483647
Year: 2007
Pages: 221

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