Book HomeActionScript: The Definitive GuideSearch this book

6.3. The ActionScript Statements

Now that you know how a typical statement is formed, skim Table 6-1 to acquaint yourself with some of the things that ActionScript statements do.

Table 6-1. The ActionScript Statements

Statement

Syntax

Use

break

break;

Cancels a loop

call

call (frame);

Executes the script on a remote frame

continue

continue;

Restarts the current loop

do-while

do {
   statements
} while (expression);

A variation of a while loop

empty statement

;

Holds a place where a statement is expected, and used with evaluate in novice mode

for

for (init; test; increment) {
   statements
}

Executes some code repetitively (a for loop)

for-in

for (property in object) {
   statements
}

Enumerates the properties of an object

function

function name(parameters) {
   statements
}

Declares a function

if-else if-else

if (expression) {
   statements
} else if (expression) {
   statements
} else {
   statements
}

Executes some code based on a condition or a series of conditions

ifFrameLoaded

ifFrameLoaded (frame) {
   statements
}

Executes some code if a certain frame has loaded; deprecated in Flash 5

return

return;
return expression;

Exits a function or returns a value from a function

set

set (variable, value);

Assigns a value to a dynamically named variable

var

var variableName;
var variableName = expression;

Declares and optionally initializes a variable

while

while (expression) {
   statements
}

Executes some code repetitively (a while loop)

with

with (objectName) {
   statements
}

Executes some code in the context of a given object

6.3.1. Loops and Conditionals

We've already had several informal encounters with loops and conditionals. Together, these two statement types account for the majority of complex flow in our programs. Loops allow us to execute statements repeatedly, and conditionals allow us to execute statements under only the specified circumstances. See Chapter 7, "Conditionals" and Chapter 8, "Loop Statements" for complete details.

6.3.2. Expression Statements

Although any expression can be used independently as a valid statement, if the expression performs no action and we don't do anything with the result, the exercise is rather pointless:

"hi there";  // This doesn't do much
345 + 5;     // Neither does this

Some expressions, however, have side effects that change the state of a system through variable or property assignments or by physically altering the Flash environment. In this example, an expression changes the value of x:

x = 345 + 5;  // Much more useful

Function calls are the most powerful type of expression statement. Even if a function doesn't return a useful value, it may have a very useful side effect. For example, gotoAndStop( ) returns the value undefined but has an important side effect -- it moves the playhead to another frame:

gotoAndStop(5);  // The value of _currentframe is changed to 5.

We'll learn more about function calls under Section 9.2, "Running Functions" in Chapter 9, "Functions".

6.3.3. The var Statement

The var statement declares a new variable:

var x;

You can assign the new variable's initial value as part of a var statement:

var x = 10;

When used outside of a function, the var statement creates a variable scoped to the timeline containing the statement. When used inside a function, the var statement creates a variable local to that function (i.e., one that dies when the function finishes). See Chapter 2, "Variables".

6.3.4. The set Statement (Set Variable)

For most variable assignments, we use an assignment expression in statement form, like this:

x = 30;

That kind of expression, however, requires us to know the name of our variable in advance. If we want to generate the name of a variable dynamically during an assignment, we can use the set statement, which has the following syntax:

set (variable, expression);

where variable is a string expression to be used as the variable name in the assignment and expression is the new value to assign to it. For example:

var x;
set ("x", 10);      // x is now 10

var firstName;
set ("first" + "Name", "jane");  // firstName is now "jane"

In the following, trickier example, y is not being set in the set statement. Instead, y 's value ("x") is retrieved and that value is used as the name of the variable to set:

// Pay close attention to this one...
var y = "x";
var x;
set(y, 15);  // x is now 15, y is still "x".

In Flash 4, set was called Set Variable. In that version of ActionScript, it was often used to dynamically assign variables that had programmatically generated sequential names. This allowed programmers to simulate arrays, which were not a native part of Flash 4 ActionScript. Since arrays were added in Flash 5, set is rarely used. For more information on simulating arrays with set, see Chapter 2, "Variables".

6.3.5. The function Statement

Just as the var statement is used to declare (i.e., create) variables, the function statement is used to declare functions. The function statement has the following syntax:

function funcName (param1, param2, param3,...paramn) {
  statements
}

The keyword function begins the statement; funcName is the name of the function being declared; param1 through paramn define the parameters required by the function when it executes; statements is a list of one or more statements that will be executed when the function is called.

The function statement creates a function for later use but does not execute that function. To execute a function, we use the function's name in a function call statement.

6.3.6. Function Call Statements

A function call statement executes a built-in or user-defined function simply by using the function's name and providing the inputs that the function needs to perform its job. The terms call, run, and invoke are often used interchangeably to mean that a function's name has been used to cause it to execute. Function call statements have the following general syntax:

funcName (arg1, arg2, ... argn);

where funcName is the name of the function we want to execute and arg1 through argn is the list of arguments (i.e., input values) that the function expects when it runs.

The function call statement is an extremely powerful and fundamental device; it's our primary means of controlling Flash movies. When we want to manipulate a movie in some way, we often call a function. Here are a few examples:

play( );                       // Plays the current movie
gotoAndStop(5);                // Sends the playhead to frame 5
startDrag("crosshair", true);  // Makes the "crosshair" instance follow
                               // the mouse pointer

Function calls are also used with objects to invoke methods:

circle.area( );
today.getDate( );

Because movie clip instances are objects, we frequently use method invocation in our scripts:

ball.play( )
intro.gotoAndStop("end");

We'll be learning more about using functions in Chapter 9, "Functions" and we'll see how functions can become object methods in Chapter 12, "Objects and Classes".

6.3.7. The call( ) Statement

On a simple level, a function is a series of reusable statements that can be executed at any time during the running of a program. Although Flash 4 did not support real functions, it did attempt to provide some of the portability of functions through remote script activation. In Flash 4 we could create something close to a function by attaching a list of statements to a frame with a label. A pseudofunction thus created could subsequently be executed via the call( ) statement:

call (frame);

The call( ) statement executes the script on the frame specified by frame, which may be any frame label or frame number. If the specified frame is not loaded, the call( ) statement fails silently.

Obviously, the pseudofunctions of Flash 4 pale in comparison with real functions, so we normally have no reason to use a call( ) statement when authoring for Flash 5 or later. But when we're authoring Flash 4 movies, we need to use the old-style subroutines and the Flash 4 call( ) statement.

6.3.8. The return Statement

When we call a function, we may optionally pass it one or more values (parameters or arguments) to manipulate during execution. A function may likewise send us back a return value (a value that results from the execution of a function and is sent back to the caller). Within the body of a function, we use the return statement to conclude the function's execution and optionally return a value. A return statement takes one of the following forms:

return;
return expression;

The optional expression, if included, becomes the return value of the function. A return statement without a return value exits the function and returns the value undefined. All return statements exit the current function. Note that return statements are not required in functions; a function without a return statement simply ends after the last statement in the function body and returns undefined. See Chapter 9, "Functions" for more details on creating, calling, and terminating functions.

6.3.9. The with Statement

The with statement provides a shorthand way to refer to properties of an object without having to retype the object's name repeatedly. A with statement takes the general form:

with (object) {
  statements
}

When a property is referenced within a with statement block, object is checked for the specified property. If the property exists in object, then object's property is used to resolve the property reference. If the property does not exist in object, the current timeline or function is consulted for the property in question.

The following example shows the difference between executing a statement inside a with statement and outside a with statement:

PI = 10;                  // Set a timeline variable, PI
with (Math) {             // Execute statements in the context of Math
  trace("pi is: " + PI);  // Displays: 3.1459... (PI is a property of Math)
}
trace("PI is: " + PI);    // Displays: 10 (Math is no longer accessed)

In addition to providing convenient access to object properties, with can be used to invoke object methods:

x = 10;
y = 11;
with (Math) {
  larger = max(x, y);
}
trace(larger);  // Displays: 11

It is not possible to define a new property on an object that is the target of a with statement. Notice in the previous example that the variable larger is not defined on the Math object, so the property reference affects the timeline or function that contains the with statement. The following code shows a misguided attempt to set a variable in myClip:

with (myClip) {
  var x = 10;  // x is set on the current timeline, not myClip
}

We can, however, legitimately use with to affect movie clip instances in other ways. It can provide a handy way to work with deeply nested instance structures. For example, we can change this:

_root.form.userProfile.userID = "U346BX";
  _root.form.userProfile.gotoAndPlay("questionnaire");

to this:

with (_root.form.userProfile) {
  userID = "U346BX";             // Resets an existing variable
                                 // in userProfile instance
  gotoAndPlay("questionnaire");  // Function applied to userProfile instance
}

But with is not our only means of achieving this convenience. We could also simply assign our instance to a variable and use that variable in our references:

var userForm = _root.form.userProfile;
userForm.useriD = "U346BX";
userForm.gotoAndPlay("questionnaire");

Many developers find the variable approach easier to read and work with, but both are valid. We'll learn more about treating movie clips as objects in Chapter 13, "Movie Clips".

6.3.10. The ifFrameLoaded Statement

The Flash 5 ifFrameLoaded statement replaces the If Frame Is Loaded Action used in prior versions. Like an if statement, ifFrameLoaded has a substatement that is executed only under certain circumstances. Here's the syntax:

ifFrameLoaded (expression) {
  statements
}

where expression must be either the number of a frame or a string indicating a frame label. If the frame indicated by expression has downloaded to the Player, statements are executed. If not, the statement block is skipped.

The ifFrameLoaded statement is awkward to use in preloading scripts because it lacks an else clause. It has, therefore, been deprecated and should be used only when authoring Flash 3 or older movies. In Flash 4 and later you should use the _totalframes and _framesloaded properties with if-else statements to create a more versatile preloader. For example:

if (_totalframes > 0 && _framesloaded == _totalframes) {
	gotoAndPlay("beginMovie");
} else {
	gotoAndPlay(_currentframe - 1);
}

6.3.11. The Empty Statement

For the sake of completeness we should mention that it is legal to issue a statement with no content via a lone semicolon:

;

The empty statement has very little practical application except that it can be used as a placeholder anywhere a statement is normally expected. It is not needed if you simply want to add blank lines to your code. ActionScript ignores blank vertical lines, which can be used to improve code readability.

In novice authoring mode, the lone semicolon appears when the evaluate Action is added to a block of code. An arbitrary statement may then be added by typing into the Expression field of the Parameters panel.



Library Navigation Links

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