Table of Contents

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 slate 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 moniker 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.

If you enter code in the Actions panel while on a frame that is not a keyframe, the code is attached to the nearest preceding keyframe.

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 can 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 you to declare variables before depositing data into them; failure to do so causes an error. ActionScript is not that strict. If we assign a value to a variable that does not exist, the interpreter creates 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 practiced throughout this book.

2.1.2 Legal Variable Names

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

These are legal variable names:

var first_name;
var counter;
var reallyLongVariableName;

These are illegal variable names that cause errors:

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

As a matter of good form, you should append suffixes to your variable names to indicate the type of information stored in the variable.

var firstName_str;               // _str means the variable contains a string
var products_array;              // _array means the variable contains an array

In Flash MX, some suffixes also activate code hinting in the Actions panel. For example, the suffix _txt in the variable name output_txt not only indicates that the variable stores a text field but also causes the Actions panel to display a quick-reference popup for text fields (the so-called code hint) when the variable name is entered. Table 2-1 lists the built-in suffixes that activate code hinting in Flash MX.

Table 2-1. Flash MX code hinting suffixes

Suffix

Datatype represented

_mc

MovieClip

_array

Array

_str

String

_btn

Button

_txt

TextField

_fmt

TextFormat

_date

Date

_sound

Sound

_xml

XML

_xmlsocket

XMLSocket

_color

Color

_video

Video

_ch

FCheckBox[1]

_pb

FPushButton[1]

_rb

FRadioButton[1]

_lb

FListBox[1]

_sb

FScrollBar[1]

_cb

FComboBox[1]

_sp

FScrollPane[1]

[1] Flash UI Components (see Appendix G)

The programming industry's most popular alternative to Flash's suggested variable naming conventions is known as Hungarian notation, developed by a Hungarian Microsoft engineer, Charles Simonyi. For information, see:

http://msdn.microsoft.com/library/techart/hunganotat.htm

For a discussion of the pros and cons of Hungarian notation, see:

http://ootips.org/hungarian-notation.html
2.1.2.1 Creating dynamically named variables

Although you'll rarely, if ever, use dynamically created variable names, it's possible to generate the name of a variable programmatically. This technique was used primarily before arrays were introduced in Flash 5, so you will often encounter it in legacy code intended for Flash 4 or earlier. To create a variable name from any expression, use the set statement. For example, here we assign the value "bruce" to the variable player1name:

var i = 1;
set ("player" + i + "name", "bruce");

Arrays and objects, discussed in later chapters, provide us with a much more powerful means of tracking dynamically named data and should be used instead of dynamic variable names.

2.1.3 Declare Variables at the Outset

It's good practice to declare your application's 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, default 5, max 10
var score = 0;       // Player's current score
var hiScore = 0;     // High score (not saved between sessions)
var player1 = "1P";  // Player's name defaults to 1P

For even tidier variable management, object-oriented programmers will want to store all variables within a class, as discussed in Chapter 12.


Table of Contents