home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeActionScript: The Definitive GuideSearch this book

1.2. Further ActionScript Concepts

You've already been introduced to many of the fundamental elements that make up ActionScript: data, variables, operators, statements, functions, and arguments. Before we delve deeper into those topics, let's sketch out the rest of ActionScript's core features.

1.2.2. Expressions

The statements of a script, as we've learned, contain the script's instructions. But most instructions are pretty useless without data. When we set a variable, for example, we assign some data as its value. When we use the trace( ) command, we pass data as an argument for display in the Output window. Data is the content we manipulate in our ActionScript code. Throughout your scripts, you'll retrieve, give, store, and generally sling around a lot of data.

In a program, any phrase of code that yields a single datum when a program runs is referred to as an expression. The number 7 and the string, "Welcome to my web site," are both very simple expressions. They represent simple data that will be used as-is when the program runs. As such, those expressions are called literal expressions, or literals for short.

Literals are only one kind of expression. A variable may also be an expression (variables stand in for data, so they count as expressions). Expressions get even more interesting when they are combined with operators. The expression 4 + 5, for example, is an expression with two operands, 4 and 5, but the plus operator makes the entire expression yield the single value 9. Complex expressions may contain other, shorter expressions, provided that the entire phrase of code can still be converted into a single value.

Here we see the variable message:

var message = "Hi there, Flash!";

If we like, we can combine the variable expression message with the literal expression " How are you?" as follows:

message + " How are you?"

which becomes "Hi there, Flash! How are you?" when the program runs. You'll frequently see long expressions include shorter expressions when working with arithmetic, such as:

(2 + 3) * (4 / 2.5) - 1

It's important to be exposed to expressions early in your programming career because the term "expression" is often used in descriptions of programming concepts. For example, I might write, "To assign a value to a variable, type the name of the variable, then an equal sign followed by any expression."

1.2.3. Two Vital Statement Types: Conditionals and Loops

In nearly all programs, we'll use conditionals to add logic to our programs and loops to perform repetitive tasks.

1.2.3.1. Making choices using conditionals

One of the really rewarding aspects of Flash programming is making your movies smart. Here's what I mean by smart: Suppose a girl named Wendy doesn't like getting her clothes wet. Before Wendy leaves her house every morning, she looks out the window to check the weather, and if it's raining, she brings an umbrella. Wendy's smart. She uses basic logic -- the ability to look at a series of options and make a decision about what to do based on the circumstances. We use the same basic logic when creating interactive Flash movies.

Here are a few examples of logic in a Flash movie:

  • Suppose we have three sections in a movie. When a user goes to each section, we use logic to decide whether to show her the introduction to that section. If she has been to the section before, we skip the introduction. Otherwise, we show the introduction.

  • Suppose we have a section of a movie that is restricted. To enter the restricted zone, the user must enter a password. If the user enters the right password, we show her the restricted content. Otherwise, we don't.

  • Suppose we're moving a ball across the screen and we want it to bounce off a wall. If the ball crosses a certain point, we reverse the ball's direction. Otherwise, we let the ball continue traveling in the direction it was going.

These examples of movie logic require the use of a special type of statement called a conditional. Conditionals let us specify the terms under which a section of code should -- or should not -- be executed. Here's an example of a conditional statement:

if (userName == "James Bond") {
  trace ("Welcome to my web site, 007.");
}

The generic structure of a conditional is:

if (this condition is met) { 
  then execute these lines of code
}

You'll learn more about the detailed syntax in Chapter 7, "Conditionals". For now, remember that a conditional allows Flash to make logical decisions.

1.2.3.2. Repeating tasks using loops

Not only do we want our movies to make decisions, we want them to do tedious, repetitive tasks for us. That is, until they take over the world and enslave us and grow us in little energy pods as . . . wait . . . forget I told you that . . . ahem. Suppose you want to display a sequence of five numbers in the Output window, and you want the sequence to start at a certain number. If the starting number were 10, you could display the sequence like this:

trace (10);
trace (11);
trace (12);
trace (13);
trace (14);

But if you want to start the sequence at 513, you'd have to retype all the numbers as follows:

trace (513);
trace (514);
trace (515);
trace (516);
trace (517);

We can avoid that retyping by making our trace( ) statements depend on a variable, like this:

var x = 1;
trace (x);
x = x + 1;
trace (x);
x = x + 1;
trace (x);
x = x + 1;
trace (x);
x = x + 1;
trace (x);

On line 1, we set the value of the variable x to 1. Then at line 2, we send that value to the Output window. On line 3, we say, "Take the current value of x, add 1 to it, and stick the result back into our variable x," so x becomes 2. Then we send the value of x to the Output window again. We repeat this process three more times. By the time we're done, we've displayed a sequence of five numbers in the Output window. The beauty being that if we now want to change the starting number of our sequence, we just change the initial value of x. Because the rest of our code is based on x, the entire sequence changes when the program runs.

That's an improvement over our first approach, and it works pretty well when we're displaying only five numbers, but it becomes impractical if we want to count to 500. To perform highly repetitive tasks, we use a loop -- a statement that causes a block of code to be repeated an arbitrary number of times. There are several types of loops, each with its own syntax. One of the most common loop types is the while loop. Here's what our counting example would look like as a while loop instead of as a series of repeated statements:

var x = 1;
while (x <= 5) {
  trace (x);
  x = x + 1;
}

The keyword while indicates that we want to start a loop. The expression (x <= 5) governs how many times the loop should execute (as long as x is less than or equal to 5), and the statements trace (x); and x = x + 1; are executed with each repetition (or iteration) of the loop. As it is, our loop saves us only 5 lines of code, but it could potentially save us hundreds of lines if we were counting to higher numbers. And our loop is flexible. To make our loop count to 500, we simply change the expression (x <=5) to (x <=500) :

var x = 1;
while (x <= 500) {
  trace (x);
  x = x + 1;
}

Like conditionals, loops are one of the most frequently used and important types of statements in programming.

1.2.4. Modular Code (Functions)

So far your longest script has consisted of four lines of code. But it won't be long before that 4 lines becomes 400 or maybe even 4,000. Sooner or later you're going to end up looking for ways to manage your code, reduce your work, and make your code easier to apply to multiple scenarios. Which is when you'll first really start to love functions. A function is a packaged series of statements. In practice, functions mostly serve as reusable blocks of code.

Suppose you want to write a quick script that calculates the area of a 4-sided figure. Without functions, your script might look like this:

var height = 10;
var width = 15;
var area = height * width;

Now suppose you want to calculate the area of five 4-sided figures. Your code quintuples in size:

var height1 = 10;
var width1 = 15;
var area1 = height1 * width1;
var height2 = 11;
var width2 = 16;
var area2 = height2 * width2;
var height3 = 12;
var width3 = 17;
var area3 = height3 * width3;
var height4 = 13;
var width4 = 18;
var area4 = height4 * width4;
var height5 = 20;
var width5 = 5;
var area5 = height5 * width5;

Because we're repeating the area calculation over and over, we are better off putting it in a function once and executing that function multiple times:

function area(height, width){
  return height * width;
}
area1 = area(10, 15);
area2 = area(11, 16);
area3 = area(12, 17);
area4 = area(13, 18);
area5 = area(20, 5);

We first created the area-calculating function using the function statement, which defines (declares) a function just as var declares a variable. Then we gave our function a name, area, just as we give variables names. Between the parentheses, we listed the arguments that our function receives every time it's used: height and width. And between the curly braces ( { }), we included the statement(s) we want our function to execute:

return height * width;

After we create a function, we may run the code it contains from anywhere in our movie by using its name. In our example we called the area( ) function five times, passing it the height and width values it expects each time: area(10, 15), area(11, 16), and so on. The result of each calculation is returned to us and we store those results in the variables area1 through area5. Nice and neat, and much less work than the non-function version of our code.

Don't fret if you have questions about this function example, as we'll learn more about functions in Chapter 9, "Functions". For now, just remember that functions give us an extremely powerful way to create complex systems. Functions help us reuse our code and package its functionality, extending the limits of what is practical to build.

1.2.6. The Event-Based Execution Model

One final topic we should consider in our overview of ActionScript fundamentals is the execution model, which dictates when the code in your movie runs (is executed). You may have code attached to various frames, buttons, and movie clips throughout your movie. But when does it all actually run? To answer that question, let's take a short stroll down computing history's memory lane.

In the early days of computing, a program's instructions were executed sequentially in the order that they appeared, starting with the first line and ending with the last line. The program was meant to perform some action and then stop. That kind of program, called a batch program, doesn't handle the interactivity required of an event-based programming environment like Flash.

Event-based programs don't run in a linear fashion as batch programs do. They run continuously (in an event loop), waiting for things (events) to happen and executing code segments in response to those events. In a language designed for use with a visual interactive environment (such as ActionScript or JavaScript), the events are typically user actions such as mouseclicks or keystrokes.

When an event such as a mouseclick occurs, the interpreter sounds an alarm. A program can then react to that alarm by asking the interpreter to execute an appropriate segment of code. For example, if a user clicks a button in a movie, we could execute some code that displays a different section of the movie (classic navigation) or submits variables to a database (classic form submission).

But programs don't react to events unless we create event handlers. Here's some pseudo-code that shows generally how event handlers are set up:

when (this event happens) { 
  execute these lines of code
}

This is typically written in the general form:

on (event) {
  statements
}

In practice, an event handler for a button that moves the playhead to frame 200 would read:

on (press) {
  gotoAndStop(200);
}

Because event-based programs are always running an event loop, ready to react to the next event, they are like living systems. Events are a crucial part of Flash movies. Without events, our scripts wouldn't do anything -- with one exception: Flash executes any code on a frame when the playhead enters that frame. The implied event is simply the playhead entering the particular frame, which is so intrinsic to Flash that no explicit event handler is required.

Events literally make things happen, which is why they come at the end of your first day of ActionScript language school. You've learned what's involved in writing scripts and what governs when those scripts will actually be executed (i.e., events). I'd say you're ready to try your first real conversation.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.