Chapter 7. Conditionals

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Part I:  ActionScript Fundamentals

Most of the code examples we've seen so far have been very linear each statement is executed in turn, starting with the first and ending with the last. Linear code always does the same thing. A conditional, in contrast, is a type of statement that performs an action only when a specified condition is met. In linear code, the interpreter might execute statement A, then statement B, then statement C. With conditional statements, we can tell the interpreter to execute statement A, then execute either statement B or statement C, depending on condition X.

We can use conditionals to create and control situations that have more than one potential outcome. For example, suppose we want to create a password-protected site. When users attempt to log in, either the password is correct and the user is allowed to enter the site, or the password is wrong and the user sees an error message. The two outcomes require two very different blocks of code in our movie's script. One block needs to send the Flash playhead to a frame containing the site's welcome screen, and the other block needs to send the playhead to a frame with an error message. But only one of the blocks should be executed when the user attempts to log in. A conditional statement allows us to execute the appropriate block and skip the inappropriate one.

How does the interpreter know which code block to execute? When we define a conditional statement, we specify the condition that must be met in order for the first block of code to be executed. If the condition is not met, an alternate block of code may be executed (and that alternate block may, in turn, have its own condition). Essentially, we set up flowchart-like logic in our program that, in pseudocode, reads like this:

if (the first condition is met) {   // Execute this code if the first condition is met } else if (the second condition is met) {   // Execute this code if the second condition is met } ...otherwise {   // Execute this code if none of the earlier conditions were met }

Of course, we must describe each condition in terms the interpreter understands. This isn't a problem it's just a question of syntax, which we'll cover next. Conceptually, all conditionals either allow or suppress the execution of a code block, based on the specified condition. Now let's see how conditionals work in practice.

     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

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