Flylib.com

Books Software

 
 
 

1.4 Onward

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin  Moock
Chapter 1.  A Gentle Introductionfor Nonprogrammers

1.4 Onward!

So how does it feel? You've learned a bunch of phrases, some grammar, some vocabulary, and even had a drawn-out conversation with Flash (the multiple-choice quiz). Quite a rich first day of language school, I'd say.

As you can see, there's a lot to learn about ActionScript, but you can also do quite a bit with just a little knowledge. Even the amount you know now will give you plenty to play around with. Throughout the rest of this book, we'll reinforce the fundamentals you've learned by exploring them in more depth and showing them in concert with real examples. Of course, we'll also cover some topics that haven't even been introduced yet.

Remember: think communication, think cooperation, and speak clearly. And if you find yourself doing any fantastically engaging work or art that you'd like to share with others, send it over to me at http://www.moock.org/contact/.

Now that you have a practical frame of reference, you'll be able to appreciate and retain the foundational knowledge detailed over the next few chapters. It will give you a deeper understanding of ActionScript, enabling you to create more complex movies.

 

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

Chapter 2. Variables

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 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 by using the variable's name—much like checking an account's 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.

 

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 2.  Variables

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:

  • Must be composed exclusively of letters , numbers , dollar signs ($) and underscores (No spaces, hyphens, or other punctuation marks are allowed.)

  • Must start with a letter, an underscore (e.g., _someVar ), or a dollar sign (e.g., $someVar )

  • 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 letters 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 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.