Book HomeActionScript: The Definitive GuideSearch this book

Chapter 2. Variables

Contents:

Creating Variables (Declaration)
Assigning Variables
Changing and Retrieving Variable Values
Types of Values
Variable Scope
Some Applied Examples
Onward!

In a typical scripted movie, we have to track and manipulate everything from frame numbers to a user's password to the velocity of a photon torpedo fired from a spaceship. In order to manage and retrieve all that information, we need to store it in variables, the primary information-storage containers of ActionScript.

A variable is a like a bank account that, instead of holding money, holds information (data). Creating a new variable is like setting up a new account; we establish a place to store something we'll need in the future. And just as every bank account has an account number, every variable has a name associated with it that is used to access the data in the variable.

Once a variable is created, we can put new data into it as often as we want -- much like depositing money into an account. Or we can find out what's in a variable using the variable's name -- much like checking an account balance. If we no longer need our variable, we can "close the account" by deleting the variable.

The key feature to note is that variables let us refer to data that either changes or is calculated when a movie plays. Just as a bank account's number remains the same even though the account balance varies, a variable's name remains fixed even though the data it contains may change. Using that fixed reference to access changing content, we can perform complex calculations, keep track of cards in a card game, save guest book entries, or send the playhead to different locations based on changing conditions.

Is that a gleam of excitement I see in your eye? Good, I thought I might have lost you with all that talk about banks. Let's start our exploration of variables by seeing how to create them.

2.1. Creating Variables (Declaration)

Creating a variable is called declaration. Declaration is the "open an account" step of our bank metaphor, where we formally bring the variable into existence. When a variable is first declared, it is empty -- a blank page waiting to be written upon. In this state, a variable contains a special value called undefined (indicating the absence of data).

To declare a new variable, we use the var statement. For example:

var speed;
var bookTitle;
var x;

The word var tells the interpreter that we're declaring a variable, and the text that follows, such as speed, bookTitle, or x, becomes our new variable's name. We can create variables anywhere we can attach code: on a keyframe, a button, or a movie clip.

We can also declare several variables with one var statement, like this:

var x, y, z;

However, doing so impairs our ability to add comments next to each variable.

Once a variable has been created, we may assign it a value, but before we learn how to do that, let's consider some of the subtler details of variable declaration.

2.1.1. Automatic Variable Creation

Many programming languages require variables to be declared before data may be deposited into them; failure to do so would cause an error. ActionScript is not that strict. If we assign a value to a variable that does not exist, the interpreter will create a new variable for us. The bank, to continue that analogy, automatically opens an account when you try to make your first deposit.

This convenience comes at a cost, though. If we don't declare our variables ourselves, we have no central inventory to consult when examining our code. Furthermore, explicitly declaring a variable with a var statement can sometimes yield different results than allowing a variable to be declared implicitly (i.e., automatically). It's safest to declare first and use later (i.e., explicit declaration), as shown throughout this book.

2.1.2. Legal Variable Names

Before running off to make any variables, be aware that variable names:

  • Must be composed exclusively of letters, numbers, and underscores. (No spaces, hyphens, or punctuation allowed.)

  • Must start with a letter or an underscore.

  • Must not exceed 255 characters. (Okay, okay, that's a lie, but reevaluate your naming scheme if your variable names exceed 255 characters.)

  • Are case-insensitive (upper- and lowercase are treated identically but you should be consistent nonetheless).

These are legal variable names:

var first_name;
var counter;
var reallyLongVariableName;

These are illegal variable names that would cause errors:

var 1first_name;                 // Starts with a number
var variable name with spaces;   // Contains spaces
var another-illegal-name;        // Contains a hyphen

2.1.3. Declare Variables at the Outset

It's good practice to declare your variables at the beginning of every movie's main script space, which is usually the first keyframe that comes after a movie's preloader. Be sure to add a comment explaining each variable's purpose for easy identification later. The beginning of a well-organized script might look like this:

// ^^^^^^^^^^^^^^^^^^^^
// Initialize variables
// ^^^^^^^^^^^^^^^^^^^^
var ballSpeed;   // Velocity of ball, max 10
var score;       // Player's current score
var hiScore;     // High score (not saved between sessions)
var player1;     // Name of player 1, supplied by user

We can give variables an initial value at the same time we create them, as follows:

var ballSpeed = 5;   // Velocity of ball, max 10
var score = 0;       // Player's current score
var hiScore = 0;     // High score (not saved between sessions)


Library Navigation Links

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