Managing Variables, Data, and Datatypes

     

Managing Variables , Data, and Datatypes

A variable is a name that you assign to a datum (data item). It's called a va riable because what it names can vary. For instance, a variable named myScore may equal 10 now. A moment later, after you've scored a point in a game, myScore may equal 11. However, in ActionScript, the variability of variables can go far beyond that: Unless you use strict data typing , you can assign different types of values to the same variable. For example, myScore could represent the number 11, then the string "foo" , and finally an array of strings and numbers .

Unintentionally changing a variable's data type can lead to errors. Strict data typing helps you avoid this potential problem, which is why strict data typing is one of the most important new features in ActionScript 2 (AS2).

Working with Variables

You can declare variables using the var keyword, as follows :

 var x; // declares the variable x with no initial value 

Implement strict typing by following the variable name with a colon and a data type, such as Number:

 var x:Number; // declares the variable x as a Number with no initial value 

You declare a variable, at most, once. Then you can use it as many times as you want throughout your program. For example:

 var x:Number = 10; // declares the variable x and sets it equal to 10 trace  (x); // displays "10" in the Output window var y:Number = x + 10; // declares the variable y and sets it equal to x + 10 trace (y); // displays "20" in the Output window 

In many programming languages, you must declare a variable before you can use it. In ActionScript, if you use a variable that has not been declared, the ActionScript interpreter creates the variable on the fly ( implicitly ).

It's good to get into the habit of declaring variables explicitly, however, and including a comment about how and where you use each variable. This coding practice makes your code more readable, and more importantly, it allows you to explicitly control the scope of variables ”that is, where within a program a variable is defined or accessible.

This section touches on the issue of scope. "Combining Statements into Functions," later in this chapter, deals with scope in more depth. See "Explicit Scoping," page 494 , and "Automatic Scoping," page 497 .


In addition, explicit declarations can be more centralized and thus easier to find. Declaring variables implicitly is like leaving tools scattered around a workshop. You can never find the one you need when you're looking for it, and you are liable to trip over one you don't want when you least expect it.

For more details on declaring variables, see "Where to Declare Variables" below.


Assigning Values to Variables

You can assign values to variables by using the assignment operator ( = ) or the set statement. For example, both of the following statements set the variable firstName equal to "John" :

 firstName = "John"; set (firstName , "John"); 

The value on the right can also be a complex expression:

 x = y + 10; set (x, y + 10); 

In the preceding examples, set adds nothing but unnecessary complexity. However, if you want to use an expression to form the variable name, set enables you to do that, whereas the assignment operator alone does not. For example, this set statement works fine:

 var i:Number = 4;set("day"+i+"night", "a French movie"); trace (day4night); // "a French movie" 

But this statement generates an error:

 "day"+i+"night" = "a French movie"; // ERROR!!! 

For more on the assignment operator, see "Using Operators," later in this chapter, page 474 .


Where to Declare Variables

Two issues generally predominate when you're deciding where to declare variables:

  • Your ability to find your variables. This is an issue of lexical program design ”how (or in this case where ) you write things down.

  • The capability of the ActionScript interpreter to find your variables when you want it to ”and not find them when you don't want it to. "Findability" or scope management is an issue of logical program design ”how the program works when it's running.

The Macromedia-recommended "best practice" from the lexical perspective is to put all or most of your code in one frame, such as the first frame of the top layer of the Main Timeline.

You can access Main Timeline variables from subclips by using _root as the path . For instance, suppose this line is on the Main Timeline:

 myVar =  20; 

Then you can access myVar from a subclip like this:

 trace(_root.myVar); // displays "20" 

You can run into problems using _root in a movie that is going to be loaded into another movie. Flash Player 7 (FP7) offers a solution in the _lockroot property of the MovieClip class. For more information, see "Loading and Unloading External Content," later in this chapter, page 520 .


In a few situations, total centralization doesn't work. When it does work, you still have to organize your code within that single container to maximize readability and minimize errors.

When Not to Centralize Code

Program design works against code centralization in at least three situations:

  • When you use a preloader , you want to get the preloader up quickly and then, in the background, do other things to initialize your program. The preloader and its variables typically take up one or more frames at the beginning of the movie. The main movie and its variables come on frame 2 or later.

  • When you use components , which combine graphics and code, you cannot centralize the component code.

  • When you use AS2 classes , each class definition is in its own file, in its own location.

The typical programmer never needs to delve into component or class code.

How to Organize Variables on the Main Timeline

Keeping a huge list of individual variables in a timeline can be like keeping kitchen utensils, piano-tuning accessories, and car repair tools all in the same drawer . Lexically, this can be hard to read. Reduce the confusion by dividing variables into categories using comments. Code for each category can also be stored and edited in an external file. You can load external files using the #include directive.

Writing all variables in one place raises logical design issues, too. For instance, each movie clip, including both its timeline and its event handlers, defines a single scope . The same applies to the Main Timeline. Within a single scope, no two program elements can have the same name. If they do, the more recently defined element will usually overwrite the one that existed previously. (In some cases, the existing name incapacitates the newer name.)

Rules for Naming Variables (and Other Things)

A variable name is an ActionScript identifier , and as such must follow three naming rules, or you risk encountering serious problems:

  • Use only letters , numbers, underscores, and dollar signs. Do not use spaces; punctuation marks such as periods, commas, hyphens, parentheses, brackets, exclamation points, or question marks; or symbols such as the following:

    ~ @ # % ^ & * = + / \ < >

  • Use a letter, underscore , or dollar sign for the initial character. Do not use a number.

  • Do not use reserved words.

ActionScript's reserved words are as follows:

add( [*] )

function

private

and( [*] )

ge( [*] )

public

break

gt( [*] )

return

case

if

static

catch

implements

super

class

import

switch

continue

in

tellTarget( [*] )

default

instanceof

this

delete

interface

throw

do

le( [*] )

try

else

lt( [*] )

typeof

eq( [*] )

ne( [*] )

var

export

new

void

finally

not( [*] )

while

for

or( [*] )

with


[*] Flash 4 reserved words deprecated since Flash 5

The following list shows words that may become reserved words in the future; you can use a word from this list now, but your program may "break" if a future version of ActionScript claims the word as its own.

abstract

enum

package

boolean

final

protected

byte

float

short

char

goto

synchronized

const

int

throws

debugger

long

transient

double

native

volatile


Other things being equal, you should follow these rules for movie clip instance names, too. Even though they are not officially identifiers, movie clip instance names often play the role of identifiers when you use them in ActionScript, and you may get errors if you don't follow the rules.

graphics/troubleshooting_icon.jpg

Having trouble with code that involves a movie clip name? See the "Troubleshooting" section at the end of this chapter, page 535 .


Many programmers also follow identifier-naming rules for other names, such as frame labels and layer names.

graphics/new_icon.jpg

In movies published for FP6, only reserved words are case sensitive. Other identifiers are not. In movies published for FP7, all identifiers are case sensitive. Thus, myVar , myvar , and Myvar do not define different variables in FP6 movies, but do in FP7 movies. Case sensitivity is required by the ECMA-262 standard and could become a requirement in future versions of ActionScript.


In either AS1 or AS2, there is at least one case- related guideline that most programmers follow: Identifiers traditionally begin with lowercase letters. The one exception is class names. Constants (variables that always retain the same value) are often written in all uppercase letters.

See Chapter 21, page 539 , for more information on classes.


Following some consistent capitalization rules is also a good idea to make your programs more readable.

Using Datatypes to Categorize Data

The most basic piece of information to know about a variable is its datatype.

In AS1, mysterious errors often result from using the wrong datatype (using a text string where ActionScript requires a number, for instance), and keeping track of datatypes can be tricky because the ActionScript interpreter sometimes does automatic datatype conversions to try to make things work. You need to understand the logic of those conversions to predict which datatypes you will end up with.

graphics/new_icon.jpg

In AS2, such problems can be eliminated by always using strict data typing. Then if you use the wrong data type, you will get an error message when you test or publish your movie.


The Nine ActionScript Datatypes

ActionScript has nine basic types of data. The five primitive datatypes, of which the most common are number and string , contain just a single primitive datum, such as a number or a single text string. The four composite datatypes ( object , array , movieclip , and function ) contain multiple pieces of data. For instance, a movie clip contains a _currentFrame property, a _name property, a _visible property, and many others.

You can determine the datatype of the value currently assigned to any variable by using the typeof operator, as follows:

 var x:Number; trace (typeof x); // no value assigned; displays "undefined" in Output window x = 2; trace (typeof x); // displays "number" in the Output window 

Table 20.1 shows the ActionScript datatypes, with their typeof return values, examples of variable assignments, and legal values for the datatypes.

Table 20.1. ActionScript Datatypes

Datatype

typeof Value

Assignment Example

Legal Values

number

"number"

var x:Number = 6;

Any number

string

"string"

var x:String = "foo";

Any character string

Boolean

"boolean"

var x:Boolean = true;

true , false

object

"object"

var x:Object = myObj;

Any object

array

"object"

var x:Array = myArray;

Any array

null

"null"

var x = null;

null

movieclip

"movieclip"

var x:MovieClip = myClip;

Any movie clip instance

function

"function"

var x:Function = myFunc;

Any function

undefined

"undefined"

var x;

undefined


Note that the variable assignment examples in Table 20.1 assume that the object, array, movie clip, and function already exist.

Also note that strict typing does not support the null or undefined values.

Number

The two most important kinds of numbers are integers , which have no fractional component (such as in “10, 0, 2, 856), and floating-point numbers ( floats ) which do have a fractional component (such as in “10.2, .01, 635.8916).

Special values for the number datatype include

  • NaN ("not a number"), which identifies non-numeric data in a datum of the Number datatype.

  • Number.MAX_VALUE , which is the largest number that ActionScript can represent (1.79769313486231e+308).

Scientific Notation

To represent very large or very small floats (whether positive or negative), ActionScript uses scientific notation, consisting of a base and an exponent, separated by the letter e ( exponent ). For instance, 123,000,000,000,000 is 1.23e+15. You can use scientific notation in your programs, too, using any float as a base. For instance, you can write 126e+3 instead of 126,000.


NOTE

Flash uses double-precision floats, meaning they can have up to 15 significant digits . Thus, in scientific notation, Flash will never use more than 15 digits in the base.


  • Number.MIN_VALUE , which is the smallest positive number that ActionScript can represent (5e-324).

  • Infinity (positive infinity), which is an indeterminate number larger than Number.MAX_VALUE .

  • -Infinity (negative infinity), which is an indeterminate number more negative than Number.MIN_VALUE .

  • Constants, such as pi and the square root of 2, which are properties of the Math object.

For more information on the Math object as well as more details on manipulating numbers with built-in functions, see "The Math Object," page 578 , in Chapter 21.


Strings

A string is any sequence of alphanumeric characters enclosed in quotation marks.

NOTE

Alphanumeric: "consisting of alphabetic and numerical symbols and of punctuation marks, mathematical symbols, and other conventional symbols used in computer work." American Heritage Dictionary of the English Language , New College Edition. Published by Houghton Mifflin Company .


Flash MX supports the double-byte character set (DBCS), or Unicode character set, for text and user interface strings.

For more on Unicode, see unicode.htm on the CD accompanying this book.


Booleans

The Boolean datatype permits only two values: true and false . The true and false values assigned to the variable can represent other concepts, such as yes and no, black and white, or up and down. The Boolean datatype is commonly used with if statements for decision-making. For instance, if the logic of your program is, "If the answer is yes, then " you would probably declare the answer variable as a Boolean:

 var answer:Boolean = true; // means the answer is "yes" 

Modeling Problem Domains Using Objects

Object is the most flexible ActionScript datatype, and the most fundamental composite datatype. The simplicity and flexibility of the Object datatypeObject datatype make it suitable for modeling almost any problem domain.

The Object datatype represents an unordered collection of properties, each of which is a name:value pair. An object property can contain any type of data that ActionScript supports.

Many of the operators commonly used with primitive datatypes don't apply to objects or other composite datatypes. For instance, you can't add, subtract, or multiply objects.

On the other hand, one operator applies only to objects (including movie clips): You use the dot ( . ) operator ”officially known as the "object property access" operator ”to how did you guess? access object properties. You can also use square brackets ”officially the "array-element/object-property" operator ”to access object properties. The general format is as follows:

  object  [  property name string  ] 

Note that the property name must be a string, meaning it must be enclosed in quotation marks. So, _root.myObj["name"] is the same as _root.myObj.name . Objects are properties of the timelines they are on, so a third way of writing the same thing is _root["myObj"]["name"] . The property name can also be represented by a variable, in which case the quotes are not present: _root.myObj[nameVar] .

You create a datum of the object type by using the new operator, like this:

 var myObj:Object = new Object(); 

Many classes of objects, such as the following three, simply display object as a typeof value.

 var badAcctError:Error = new Error(); // new object in the Error class var newsFeedXML:XML = new XML(); // new object in the XML class var myArray:Array = new Array(); // new object in the Array class 

Array

An array is an ordered list. For instance, you could use an array to store the names of days of the week or months of the year. Items in the list ( elements ) are accessed via numerical indices. In ActionScript, the initial index is always 0. Here, you assign a value, "Monday" , to the first element of an array, myArray , and display that value in the Output window:

 myArray[0] = "Monday"; trace (myArray[0]); // "Monday" 

The array is actually a special case of the Object datatypeObject datatype . As with objects, you use the new operator to create arrays. You can use all the same operators with arrays as with objects, with the exception of the dot ( . ) operator, which is reserved for objects (including movie clips).

Like objects, arrays can hold any kind of ActionScript data.

The numerical indices used to access arrays offer some possibilities that do not exist with objects. These possibilities are discussed in "The Array Class," page 557 , in Chapter 21, "Advanced ActionScript").


null

The null datatype permits just one value: the primitive value null . You assign this value to a data container (such as a variable, object property, or array element) to indicate that the container is empty. You can also assign the null value to an identifier used as a function name, thus disabling the function.

The null datatype is closely related to the undefined datatype, as shown by the fact that the ActionScript interpreter sees them as equal:

 trace (null == undefined); // "true" 

There is nothing else (except null itself) that the interpreter considers equal to null . For example:

 trace (null ==); // "false"  the empty string is not equal to null 

For more information on the distinction between null and undefined , see "Using null and undefined," later in this chapter, page 471 .


movieclip

The MovieClip datatype is familiar to every Flash programmer. Its main distinguishing features are a timeline and graphical content, which can be controlled via the movie clip's properties. Thus, for instance, a movie clip is the only built-in object in Flash that has color , position, rotation, scale, size , or transparency. Adding this datatype is one of the ways in which Macromedia went beyond the ECMA-262 standard in creating a scripting language for Flash.

Function

A function is a named block of ActionScript code that performs a particular task. A number of global functions, such as trace() , are not properties of any object. Functions that are properties of objects are called methods . For instance, gotoAndStop() is a MovieClip method that causes a movie clip to go to a particular frame in its timeline and stop.

Often, a function takes one or more arguments as input and returns a datum. For example, isNaN() is a global function that takes any expression as an argument and returns a Boolean true if the expression, when treated as a number, resolves to the special value NaN (not a number), or false if the expression does not resolve to NaN .

Although it's not usually as evident as it is with arrays, the Function datatype is actually a special case of the Object datatype, too. For example, although programmers don't often take advantage of this capability, functions can have properties, accessible via the same dot and square bracket operators used for the Object datatype.

Despite these object-like characteristics, you can't create or remove functions programmatically: The new and delete operators do not work with functions.

undefined

Like the null datatype, the undefined datatype indicates an absence of data. However, whereas you assign the null value yourself, the intention is that only the ActionScript interpreter will assign the undefined value as a default when you don't assign a value to a variable or other data container. For example:

 var middleName:String; trace (middleName);  // "undefined" 

The ActionScript interpreter also returns undefined if you reference a variable or other data container that does not exist. (JavaScript generates an error under these conditions.)

See "Using null and undefined," page xxx , later in this chapter, for more details on the distinction between null and undefined .


Explicit and Implicit Data Conversion

After a variable has been declared, whether with or without strict data typing, you can explicitly change its datatype, a process called casting (or typecasting ). You typecast using functions such as Boolean() , Number() , String() , and toString() . For instance, if you declare var mc:MovieClip; with no value, then, in Flash Player 7

  • Boolean(mc) is equal to false , because undefined becomes false as a Boolean.

  • String(mc) is equal to the string "undefined" . (In FP6, it's equal to the empty string.)

  • Number(mc) is equal to NaN , because undefined becomes NaN as a Number. (In FP6, it becomes zero.)

NOTE

Because of differences in the ways different versions of the Flash Player evaluate undefined , you should use the typeof operator to determine whether a datum is of the undefined datatype:

 if (typeof middleName == "undefined"); 


Casting doesn't always work as you might expect or hope. For instance, the string "six" cannot be successfully converted to a number (it becomes NaN ), but the numeral 6 can. On the other hand, any number can be converted to a string; for instance, the number 6 becomes the string "6" .

However, casting never yields an error, even if you're using strict data typing. Instead, the ActionScript interpreter assigns a new value to the variable based on its own rules, some of which are illustrated in the previous examples.

Datatype conversion rules are discussed in Appendix A, "ActionScript Reference," under "Datatype Conversion Rules," page 911 .


The same rules apply if you're not using strict data typing or casting, and you simply use a variable in a new context. This is called implicit datatype conversion.

Implicit datatype conversion can happen without your being aware of it and therefore may produce results you aren't expecting. That's why it's helpful to use strict data typing.

Explicit datatype conversion (that is, casting) is less likely to cause trouble because you are always aware that you have done it.

Numbers and Strings versus Numeric and String Literals

A variable is an abstract representation of a datum. It in no way resembles the datum itself. In contrast, a literal represents a datum literally, not abstractly, and the ActionScript interpreter actually creates the datum using only the literal as a blueprint.

In the following example, x is a variable. "Howdy Pete" is a string literal:

 x = "Howdy Pete!" 

A variable is a number if its assigned value is a numeric literal. It is also a number if its assigned value is a complex expression that can be reduced to a numeric literal. For instance:

 x = 3 + 3; // can be reduced to a numeric literal: 6 

Literals cannot span multiple lines of code. For instance, the following will not work:

 test = "Howdy Pete!"; 

You can use the plus ( + ) operator to get around this limitation:

 test = "Howdy " +      "Pete!"; 

A string or numeric literal may be used for a temporary purpose, without being stored. If you want to reuse the datum represented by a string or numeric literal, you must store it in a variable, array element, or object property. Unless it is stored, a literal does not persist and is of no further use.

Object and Array Literals

An array is a named, ordered list whose elements are accessed via numeric indices. An array literal is a comma-separated list of the elements, enclosed in square brackets, without the array name or the indices. For instance, here are the first three values of an array of strings representing the months:

 months[0] = "January"; months[1] = "February"; months[2] = "March"; 

The corresponding array literal looks like this:

 ["January" , "February" , "March"] 

You can create an array by assigning the anonymous, nameless array literal to a variable, which thereby becomes an array name:

 months = ["January" , "February" , "March"]; 

Similarly, an object is a named, unordered list whose properties are accessed by name. For instance, here are the properties of a computer object:

 computer.monitor = "SVGA"; computer.processor = "Pentium 4"; computer.price = 1700; 

The corresponding object literal is a comma-separated list of properties enclosed in curly braces, without the object name. Each property consists of a name and a value, separated by a colon. For instance:

 { monitor : "SVGA" , processor : "Pentium 4" , price : 1700 } 

You can assign the object literal to a variable, which thereby becomes an object name:

 computer = { monitor : "SVGA" , processor : "Pentium 4" , price : 1700 }; 

As with string and numeric literals, array and object literals are lost if they are not assigned to a variable or stored in an array element or an object property.

NOTE

The object literal format provides a good visual representation of an object, and the property:value syntax is a concise way of referring to objects and properties.


Using null and undefined

Both null and undefined are extremely useful to the programmer, but their uses are different, even though both indicate an absence of data. The null value is used in messages from the programmer to the interpreter. The undefined value should be reserved for messages from the interpreter to the programmer.

The ActionScript interpreter assigns the undefined datatype as a default when you don't assign any content to a declared variable. A declaration of this sort is shown in line 1 in the following example. The interpreter also returns undefined if you ask for the type of a variable that does not exist. This is illustrated in line 7.

Assigning the value undefined to a variable is legal but not recommended. (This poor practice is shown in line 5.) If you refrain from assigning the undefined datatype, you will always know when you see it that the interpreter has assigned it automatically. When you want to assign a value to a variable to indicate that it contains no data, use null . Then undefined will always indicate exactly what the word implies: something that has never been defined.

 1: var x:Number;                      // OK 2: trace (typeof x);           // "undefined" 3: x = null;                   // OK 4: trace (typeof x);           // "null" 5: x = undefined;              // legal but poor practice !!! 6: trace (typeof x);           // "undefined" : no value assigned 7: trace (typeof y);           // "undefined" : doesn't exist 



Using Macromedia Studio MX 2004
Special Edition Using Macromedia Studio MX 2004
ISBN: 0789730421
EAN: 2147483647
Year: N/A
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net