What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

Learn Syntax and Language Fundamentals in Flash

About syntax, statements, and expressions

Differences between ActionScript and JavaScript

About case sensitivity

About dot syntax and target paths

About using dot syntax to target an instance

Targeting an instance

Targeting dynamic instances and loaded content

About scope and targeting

Using the Target Path button

About slash syntax

Semicolons and colons

Curly braces

Parentheses

About literals

About comments

Single-line comments

Multiline comments

Trailing comments

Comments inside classes

About constants and keywords

Using constants

Using variables in an application

About keywords

About statements

About compound statements

About conditions

About writing conditions

Using the if statement

Using the if..else statement

Using the if..else if statement

Using a switch statement

Using try..catch and try..catch..finally statements

About the conditional operator and alternative syntax

Repeating actions using loops

About creating and ending loops

About creating and ending loops

About casting objects

Using for loops

Using for..in loops

Using while loops

About do..while loops

Using nested loops in your ActionScript

About arrays

Using arrays

About modifying arrays

About referencing and finding length

About adding and removing elements

Creating indexed arrays

Creating multidimensional arrays

Creating associative arrays

About operators

Using operators to manipulate values

About operator precedence and associativity

About using operators with strings

Using dot and array access operators

About postfix operators

About unary operators

About multiplicative operators

About additive operators

Using numeric operators

About relational operators

About equality operators

Using relational and equality operators

About assignment operators

Using assignment operators

About logical operators

Using operators in a document

About bitwise shift operators

About bitwise logical operators

About relational operators

About the conditional operator

Using operators in a document

About syntax, statements, and expressions

TOP

The ActionScript language is made up of the built-in classes that make up the ActionScript language. You need to use correct ActionScript syntax to form statements so the code compiles and runs correctly in Flash. In this case, syntax refers to the grammar and spelling of a language that you program with. The compiler cannot understand incorrect syntax, so you see errors or warnings displayed in the Output panel when you try to test the document in the test environment. Therefore, syntax is a collection of rules and guidelines that help you form correct ActionScript.

A statement is an instruction you give the FLA file to do something, such as to perform a particular action. For example, you can use a conditional statement to determine whether something is true or exists. Then you might execute actions that you specify, such as functions or expressions, based on whether the condition is true or not. The if statement is a conditional statement and evaluates a condition to determine the next action that should occur in your code.

// if statement

if (condition) {

// statements;

}

Expressions, different from statements, are any legal combination of ActionScript symbols that represent a value. Expressions have values, while values and properties have types. An expression can consist of operators and operands, values, functions, and procedures. The expression follows ActionScript rules of precedence and of association. Typically, Flash Player interprets the expression and then returns a value that you can use in your application.

For example, the following code is an expression:

x + 2

In the previous expression, x and 2 are operands and + is an operator.

The way you format your ActionScript also determines how maintainable your code is. For example, it's difficult to read the logic of a FLA file that doesn't contain indents or comments, or contains inconsistent formatting and naming conventions. When you indent blocks of ActionScript (such as loops and if statements), the code is easier to read and debug if you encounter problems.

 

Differences between ActionScript and JavaScript

TOP

ActionScript is similar to the core JavaScript programming language. You don't need to know JavaScript to use and learn ActionScript; however, if you know JavaScript, ActionScript will seem familiar.

This manual does not attempt to teach general programming. There are many resources that provide more information about general programming concepts and the JavaScript language.

  • The ECMAScript (ECMA-262) edition 3 language specification is derived from JavaScript and serves as the international standard for the JavaScript language. ActionScript is based on this specification.

  • The Java Technology site has tutorials on object-oriented programming that are targeted for the Java language but are useful for understanding concepts that you can apply to ActionScript.

Some of the differences between ActionScript and JavaScript are described in the following list:

  • ActionScript does not support browser-specific objects such as Document, Window, and Anchor.

  • ActionScript does not completely support all the JavaScript built-in objects.

  • ActionScript does not support some JavaScript syntax constructs, such as statement labels.

  • In ActionScript, the eval() function can perform only variable references.

  • ActionScript 2.0 supports several features that are not in the ECMA-262 specification, such as classes and strong typing. Many of these features are modeled after the ECMAScript (ECMA-262) edition 3 language specification

  • ActionScript does not support regular expressions using the RegExp object. However, Macromedia Central does support the RegExp object.

 

About case sensitivity

TOP

When you write ActionScript for Flash Player 7 and later, your code is case-sensitive. This means that variables with slightly different capitalization are considered different from each other. The following ActionScript code shows this:

// use mixed capitalization

var firstName:String = "Jimmy";

// use all lower case

trace(firstname); // undefined

Or you could write the following:

// In file targeting Flash Player 8

// and either ActionScript 1.0 or ActionScript 2.0

//

// Sets properties of two different objects

cat.hilite = true;

CAT.hilite = true;

// Creates three different variables

var myVar:Number = 10;

var myvar:Number = 10;

var mYvAr:Number = 10;

NOTE : It is not a good practice to differentiate between variables, or any identifier, using different case.

When you publish for versions of Flash Player (Flash Player 6 and earlier), Flash traces the string Jimmy in the Output panel. Because Flash Player 7 and later versions are case-sensitive, firstName and firstname are two separate variables (when you use either ActionScript 1.0 or ActionScript 2.0). This is an important concept to understand. If you created FLA files for Flash Player 6 or earlier with nonmatching capitalization in your variables, your functionality and files might break during conversion of the file or application that targets a newer version of the Flash Player.

Therefore, it's good practice to follow consistent capitalization conventions, such as those used in this manual. Doing so also makes it easier to differentiate between variables, classes, and function names. Do not use case to make two identifiers differ. Change the instance, variable, or class name--not just the case.

Case sensitivity can have a large impact when you work with a web service that uses its own rules for variable naming and for the case that variables are in when they are returned to the SWF file from the server. For example, if you use a ColdFusion web service, property names from a structure or object might be all uppercase, such as FIRSTNAME. Unless you use the same case in Flash, you might experience unexpected results.

NOTE : Case sensitivity also affects external variables that you load into a SWF file, such as those loaded with LoadVars.load().

Case sensitivity is implemented for external scripts, such as ActionScript 2.0 class files, scripts that you import using the #include command, and scripts in a FLA file. If you encounter runtime errors and are exporting to more than one version of Flash Player, you should review both external script files and scripts in FLA files to confirm that you used consistent capitalization.

Case sensitivity is implemented on a per-SWF file basis. If a strict (case-sensitive) Flash Player 8 application calls a nonstrict Flash Player 6 SWF file, ActionScript executed in the Player 6 SWF file is nonstrict. For example, if you use loadMovie() to load a Flash Player 6 SWF file into a Flash Player 8 SWF file, the version 6 SWF file remains case-insensitive, while the version 8 SWF file is treated as case-sensitive.

When syntax coloring is enabled, language elements written with correct capitalization are blue by default.

 

About dot syntax and target paths

TOP

In ActionScript, you use a dot (.) operator (dot syntax) to access properties or methods that belong to an object or instance on the Stage. You also use the dot operator to identify the target path to an instance (such as a movie clip), variable, function, or object.

A dot syntax expression begins with the name of the object or movie clip, followed by a dot, and it ends with the element you want to specify. The following sections demonstrate how to write dot syntax expressions.

To control a movie clip, loaded SWF file, or button, you must specify a target path. Target paths are hierarchical addresses of movie clip instance names, variables, and objects in a SWF file. In order to specify a target path for a movie clip or button, you must assign an instance name to the movie clip or button. You name a movie clip instance by selecting the instance and typing the instance name in the Property inspector. Or you can specify the instance name with code if you create the instance using ActionScript. You can use the target path to assign an action to a movie clip or to get or set the value of a variable or property.

 

About using dot syntax to target an instance

TOP

To write ActionScript that controls an instance such as a movie clip or manipulates assets in a loaded SWF file, you must specify its name and its address in code. This is called a target path. To target (or address) objects in a SWF file, you use dot syntax (also called dot notation). For example, you need to target a movie clip or button instance before you can apply an action to it. Dot syntax helps you create a path to the instance you need to target. The path to the instance that you target is sometimes called the target path.

A FLA file has a particular hierarchy. You can create instances on the Stage or you can use ActionScript. You can even create instances that are inside other instances. Or you might have instances that nest within several other instances. You can manipulate any instance as long as you name it.

You name instances using an instance name, which you can specify in two different ways (both demonstrated below):

  • Manually by selecting an instance and typing an instance name in the Property inspector (when an instance is on the Stage).

  • Dynamically by using ActionScript. You create an instance using ActionScript and assign it an instance name when you create it.

To assign the instance an instance name in the Property inspector, type a name into the Instance Name text box.

You can also give an instance name to an object you create using ActionScript. It can be as simple as the following code:

this.createEmptyMovieClip("pic_mc", this.getNextHighestDepth());

pic_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");

This code creates a new movie clip and assigns it the instance name pic_mc. Then, you can manipulate the pic_mc instance using code, such as loading an image into it as demonstrated in the previous code.

 

Targeting an instance

TOP

If you want something to work in your SWF file, you need to target that instance and then tell it to do something, such as assigning it an action or changing its properties. You usually need to define where that instance is in the SWF file (for example, what timeline it's on or what instance it's nested within) by creating the target path. Remember that you have given many of the instances in your FLA file instance names, and then you added code to the FLA file that uses those instance names. When you do this, you target that particular instance and then tell it to do something (such as move the playhead or open a web page). For more information on objects and properties, see Object data type.

To target an instance:

  1. Select File > New and select Flash Document.

  2. Select File > Save As and name the file target.fla.

  3. Use the Oval tool to draw a shape on the Stage. Draw an oval of any size and color.

  4. Use the Selection tool to select the oval on the Stage.

    TIP : Remember to select the stroke and fill if necessary.

  5. Select Modify > Convert to Symbol, select the Movie Clip option, and then click OK to create the symbol.

  6. Select the movie clip on the Stage and give it the instance name myClip in the Property inspector.

  7. Insert a new layer and rename the layer actions.

  8. Add the following ActionScript to Frame 1 of the actions layer:

    myClip._xscale = 50;

This line of code targets the myClip instance on the Stage. The ActionScript scales the instance to half its original width. Because the ActionScript is on the same timeline as the movie clip symbol, you only need to target the instance using the instance name. If the instance was on a different timeline or nested within another instance, you would need to modify the target path accordingly.

Targeting a nested instance

You can also target instances that are nested inside other instances. Perhaps you want to place a second movie clip instance inside of the myClip instance from the exercise in Targeting an instance. You can also target that nested instance using ActionScript. Before you proceed with the following exercise, you need to complete the exercise in Targeting an instance, and then follow these steps to target a nested instance.

To target a nested instance:

  1. Open target.fla from the procedure on targeting an instance, and rename it target2.fla.

  2. Double-click the myClip instance on the Stage.

  3. Select the Oval tool and draw another oval inside of the myClip instance.

  4. Select the new shape, and then select Modify > Convert to Symbol.

  5. Select the Movie Clip option and click OK.

  6. Select the new instance, and type myOtherClip in the Instance Name text box of the Property inspector.

  7. Click Scene 1 in the edit bar to return to the main Timeline.

  8. Add the following ActionScript to Frame 1 of the actions layer:

    myClip.myOtherClip._xscale = 50;

    This ActionScript resizes the myOtherClip instance to 50% of its current width. Because the target.fla file modified the myClip instances _xscale property, and the myOtherClip is a nested symbol, you'll notice that myOtherClip will be 25 percent of the original width.

If you work with nested movie clips that have their own timelines, you can manipulate the playhead in a nested instance's timeline using code similar to the following snippet:

myClip.nestedClip.gotoAndPlay(15);

myClip.someOtherClip.gotoAndStop("tweenIn");

Notice that the clip that you manipulate (such as nestedClip) appears right before the action. You'll notice this trend in upcoming sections.

You aren't limited to accessing predefined methods and properties of instances on the Stage, as demonstrated in the previous examples. You can also set a variable within a movie clip, as seen in the following code, which sets a variable in the starClip movie clip:

starClip.speed = 1.1;

starClip.gravity = 0.8;

If either the speed or gravity variables existed previously in the starClip movie clip instance, the previous values would have been overwritten as soon as the new values were set. You are able to add new properties to the starClip movie clip, because the MovieClip class was defined with the dynamic keyword. The dynamic keyword specifies that objects based on the specified class (in this case MovieClip) can add and access dynamic properties at runtime.

 

Targeting dynamic instances and loaded content

TOP

You can also create an object using ActionScript and target it using a target path afterwards. For example, you can use the following ActionScript to create a movie clip. Then you can chang the rotation of that movie clip using ActionScript, as shown in the next example:

To target a dynamically created movie clip instance:

  1. Create a new Flash document and save the file as targetClip.fla.

  2. Insert a new layer and rename the layer actions.

  3. Add the following ActionScript to Frame 1 of the actions layer:

    this.createEmptyMovieClip("rotateClip", this.getNextHighestDepth());

    trace(rotateClip);

    rotateClip._rotation = 50;

  4. Select Control > Test Movie to test your document.

    You can tell that you created a movie clip because of the trace statement, but you cannot see anything on the Stage. Even though you added code that creates a movie clip instance, you won't see anything on the Stage unless you add something to the movie clip. For example, you might load an image into the movie clip.

  5. Return to the authoring environment, and open the Actions panel.

  6. Type the following ActionScript after the code you added in step 3:

    rotateClip.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");

    This code loads an image into the rotateClip movie clip that you created with code. You're targeting the rotateClip instance with ActionScript.

  7. Select Control > Test Movie to test your document.

    Now you should see an image on the Stage that rotates 50 clockwise.

You can also target or identify parts of SWF files that you load into a base SWF file.

To identify a loaded SWF file:

  • Use _levelX, where X is the level number specified in the loadMovie() function that loaded the SWF file.

    For example, a SWF file loaded into level 99 has the target path _level99. In the following example, you load a SWF file into level 99 and set its visibility to false:

    //Load the SWF onto level 99.

    loadMovieNum("contents.swf", 99);

    //Set the visibility of level 99 to false.

    loaderClip.onEnterFrame = function(){

    _level99._visible = false;

    };

TIP : It's generally a good idea to avoid using levels if you can load content into movie clips at different depths instead. Using the MovieClip.getNextHighestDepth() method enables you to create new movie clip instances on the Stage dynamically without having to check whether there is already an instance at a particular depth.

Setting variables using a path

You can set variables for instances that you nest inside of other instances. For example, if you want to set a variable for a form that's inside another form, you can use the following code. The instance submitBtn is inside of formClip on the main timeline:

this.formClip.submitBtn.mouseOver = true;

You can express a method or property of a particular object (such as a movie clip or text field) using this pattern. For example, the property of an object would be

myClip._alpha = 50;

 

About scope and targeting

TOP

When you nest instances, the movie clip that nests a second movie clip is known as the parent to the nested instance. The nested instance is known as the child instance. The main Stage and main timeline are essentially a movie clip themselves, and can therefore be targeted as such.

You can target parent instances and parent timelines using ActionScript. When you want to target the current timeline, you use the this keyword. For example, when you target a movie clip called myClip that's on the current main timeline, you would use

this.myClip.

Optionally, you can drop the this keyword, and just use

myClip

You might choose to add the this keyword for readability and consistency.

If you trace the movie clip, for either snippet above you see _level0.myClip in the Output panel. However, if you have ActionScript that's inside the myClip movie clip but you want to target the main timeline, target the parent of the movie clip (which is the main Stage). Double-click a movie clip, and place the following ActionScript on the movie clip's timeline:

trace("me: " + this);

trace("my parent: " + this._parent);

Test the SWF file, and you'll see the following message in the Output panel:

me: _level0.myClip

my parent: _level0

This indicates you targeted the main timeline. You can use parent to create a relative path to an object. For example, if the movie clip dogClip is nested inside the animating movie clip animalClip, the following statement on the instance dogClip tells animalClip to stop animating:

this._parent.stop();

If you're familiar with Flash and ActionScript, you've probably noticed people using the _root scope. The _root scope generally refers to the main timeline of the current Flash document. You should avoid using the _root scope unless it's absolutely necessary. You can use relative target paths instead of _root.

If you use _root in your code, you can encounter errors if you load the SWF file into another Flash document. When the SWF file loads into a different SWF file, _root in the loaded file might point to the root scope of the SWF file it loads into, instead of referring to its own root as you intend it to. This can lead to unpredictable results, or break functionality altogether.

 

Using the Target Path button

TOP

Sometimes it takes some time to figure out what a given target path is, or what target path you need for a piece of code. If you target an instance you have on the Stage, you can use the Target Path button to determine what the path is to that instance.\

To use the Target Path button:

  1. Open the Actions panel (Window > Actions) and click the Insert Target Path button. The movie clips in your current document appear in a dialog box.

  2. Select one of the instances from the list in the dialog box.

  3. Click OK.

  4. The target path for the selected instance appears in the Script pane.

 

About slash syntax

TOP

Slash syntax was used in Flash 3 and 4 to indicate the target path of a movie clip or variable. This syntax is supported by ActionScript 1.0 in Flash Player 7 and earlier, but it's not supported in ActionScript 2.0 and Flash Player 7 or Flash Player 8.

Using slash syntax is not recommended unless you do not have another option, such as when you create content intended specifically for Flash Player 4 or Flash Lite 1.1 (and earlier) where you must use slash syntax.

 

Semicolons and colons

TOP

ActionScript statements terminate with a semicolon (;) character, as demonstrated in the following two lines of code:

var myNum:Number = 50;

myClip._alpha = myNum;

You can omit the semicolon character and the ActionScript compiler assumes that each line of code represents a single statement. However, it is good scripting practice to use semicolons because it makes your code more readable. When you click the Auto Format button in the Actions panel or Script window, trailing semicolons are appended to the end of your statements by default.

NOTE : Using a semicolon to terminate a statement allows you to place more than one statement on a single line, but doing so usually makes your code more difficult to read.

Another place you use semicolons is in for loops. You use the semicolon to separate parameters, as shown in the following example. The example loops from 0 to 9 and then displays each number in the Output panel:

var i:Number;

for (i = 0; i < 10; i++) {

trace(i); // 0,1,...,9

}

You use colons (:) in your code to assign data types to your variables. To assign a specific data type to an item, specify its type using the var keyword and post-colon syntax, as shown in the following example:

// strict typing of variable or object

var myNum:Number = 7;

var myDate:Date = new Date();

// strict typing of parameters

function welcome(firstName:String, myAge:Number) {

}

// strict typing of parameter and return value

function square(num:Number):Number {

var squared:Number = num * num;

return squared;

}

You can declare the data type of objects based on built-in classes (Button, Date, MovieClip, and so on) and on classes and interfaces that you create. In the following snippet, you create a new object of the custom type Student:

var firstStudent:Student = new Student();

You can also specify that objects are of the Function or the Void data type.

 

Curly braces

TOP

You group ActionScript events, class definitions, and functions into blocks using curly brace ({}) punctuators. You put the opening brace on the same line as the declaration.

NOTE : You can also put the opening brace on the line that follows the declaration. Coding conventions recommend that you put the opening brace on the same line for consistency.

Place braces around each statement when it is part of a control structure (such as if..else or for), even if it contains only a single statement. This good practice helps you avoid errors in your ActionScript when you forget to add braces to your code. The following example shows code that is written using poor form:

var numUsers:Number;

if (numUsers == 0)

trace("no users found.");

Although this code validates, it is considered poor form because it lacks braces around the statements.

TIP : Braces are added to this statement if you click the Check Syntax button.

In this case, if you add a second statement after the trace statement, the second statement executes regardless of whether the numUsers variable equals 0, which can lead to unexpected results. For this reason, add braces so the code looks like the following example:

var numUsers:Number;

if (numUsers == 0) {

trace("no users found");

}

In the following example, you create both an event listener object and a MovieClipLoader instance.

var imgUrl:String = "http://www.helpexamples.com/flash/images/image1.jpg";

this.createEmptyMovieClip("img_mc", 100);

var mclListener:Object = new Object();

mclListener.onLoadStart = function() {

trace("starting");

};

mclListener.onLoadInit = function(target_mc:MovieClip):Void {

trace("success");

};

mclListener.onLoadError = function(target_mc:MovieClip):Void {

trace("failure");

};

var myClipl:MovieClipLoader = new MovieClipLoader();

myClipl.addListener(mclListener);

myClipl.loadClip(imgUrl, img_mc);

The next example displays a simple class file that could be used to create a Student object. You learn more about class files in Classes.

To use curly braces in an ActionScript file:

  1. Select File > New and then select ActionScript File.

  2. Select File > Save As and save the new document as Student.as.

  3. Add the following ActionScript to the AS file.

    // Student.as

    class Student {

    private var _id:String;

    private var _firstName:String;

    private var _middleName:String;

    private var _lastName:String;

    public function Student(id:String, firstName:String, middleName:String, lastName:String) {

    this._id = id;

    this._firstName = firstName;

    this._middleName = middleName;

    this._lastName = lastName;

    }

    public function get firstName():String {

    return this._firstName;

    }

    public function set firstName(value:String):Void {

    this._firstName = value;

    }

    // ...

    }

  4. Save the class file.

  5. Select File > New and click Flash Document to create a new FLA file.

  6. Save the new FLA file as student_test.fla.

  7. Type the following ActionScript on Frame 1 of the main Timeline:

    // student_test.fla

    import Student;

    var firstStudent:Student = new Student("cst94121", "John", "H.", "Doe");

    trace(firstStudent.firstName); // John

    firstStudent.firstName = "Craig";

    trace(firstStudent.firstName); // Craig

  8. Select File > Save to save the changes to student_test.fla.

  9. Select Control > Test Movie to test the FLA and AS files.

The next example demonstrates how curly braces are used when you work with functions.

To use curly braces with functions:

  1. Select File > New and select Flash Document to create a new FLA file.

  2. Select File > Save As and name the new file checkform.fla.

  3. Drag an instance of the Label component from the Components panel onto the Stage.

  4. Open the Property inspector (Window > Properties > Properties) and with the Label component instance selected, type an instance name of status_lbl into the Instance Name text box.

  5. Type 200 into the W (width) text box to resize the component to 200 pixels wide.

  6. Drag an instance of the TextInput component onto the Stage and give it an instance name of firstName_ti.

  7. Drag an instance of the Button component onto the Stage and give it an instance name of submit_button.

  8. Select Frame 1 of the Timeline, and add the following ActionScript into the Actions panel:

    function checkForm():Boolean {

    status_lbl.text = "";

    if (firstName_ti.text.length == 0) {

    status_lbl.text = "Please enter a first name.";

    return false;

    }

    return true;

    }

    function clickListener(evt_obj:Object):Void {

    var success:Boolean = checkForm();

    };

    submit_button.addEventListener("click", clickListener);

  9. Select File > Save to save the Flash document.

  10. Select Control > Test Movie to test the code in the authoring environment.

    In the SWF file, an error message is displayed if you click the Button instance on the Stage when you do not have text in the firstName_ti TextInput component. This error appears in the Label component and informs users that they need to enter a first name.

The next example using curly braces shows how to create and define properties within an object. In this example, properties are defined in the object by specifying the variable names within the curly brace ({}) punctuators:

var myObject:Object = {id:"cst94121", firstName:"John", middleName:"H.", lastName:"Doe"};

var i:String;

for (i in myObject) {

trace(i + ": " + myObject[i]);

}

/*

id: cst94121

firstName: John

middleName: H.

lastName: Doe

*/

You can also use empty curly braces as a syntax shortcut for the new Object() function. For example, the following code creates an empty Object instance:

var myObject:Object = {};

TIP : Remember to make sure each opening curly brace has a matching closing brace.

 

Parentheses

TOP

When you define a function in ActionScript, you place parameters inside parentheses [()] punctuators, as shown in the following lines of code:

function myFunction(myName:String, myAge:Number, happy:Boolean):Void {

// Your code goes here.

}

When you call a function, you also include any of the parameters you pass to the function in parentheses, as shown in the following example:

myFunction("Carl", 78, true);

You can use parentheses to override the ActionScript order of precedence or to make your ActionScript statements easier to read. This means you can change the order in which values are computed by placing brackets around certain values, as seen in the following example:

var computedValue:Number = (circleClip._x + 20) * 0.8;

Because of order of precedence, if you didn't use parentheses or use two separate statements, the multiplication would be computed first, meaning that the first operation would be 20 * 0.8.

The result, 16, would then be added to the current value of circleClip._x and finally assigned to the computedValue variable.

If you don't use parentheses, you must add a statement to evaluate the expression, as shown in the following example:

var tempValue:Number = circleClip._x + 20;

var computedValue:Number = tempValue * 0.8;

As with brackets and braces, you need to make sure each opening parentheses has a closing parentheses.

 

About literals

TOP

A literal is a value that appears directly in your code. Literals are constant (unchanging) values within your Flash documents. Examples of a literal include true, false, 0, 1, 52, or even the string "foo".

The following examples are all literals:

17
"hello"
-3
9.4
null
undefined
true
false

Literals can also be grouped to form compound literals. Array literals are enclosed in bracket punctuators ([]) and use the comma punctuator (,) to separate array elements. An array literal can be used to initialize an array. The following examples show two arrays that are initialized using array literals. You can use the new statement and pass the compound literal as a parameter to the Array class constructor, but you can also assign literal values directly when instantiating instances of any built-in ActionScript class.

// using new statement
var myStrings:Array = new Array("alpha", "beta", "gamma");
var myNums:Array = new Array(1, 2, 3, 5, 8);

// assigning literal directly
var myStrings:Array = ["alpha", "beta", "gamma"];
var myNums:Array = [1, 2, 3, 5, 8];

Literals can also be used to initialize a generic object. A generic object is an instance of the Object class. Object literals are enclosed in curly braces ({}) and use the comma punctuator (,) to separate object properties. Each property is declared with the colon punctuator (:), which separates the name of the property from the value of the property.

You can create a generic object using the new statement and pass the object literal as a parameter to the Object class constructor, or you can assign the object literal directly to the instance you are declaring. The following example creates a new generic object and initializes the object with three properties, propA, propB, and propC, each with values set to 1, 2, and 3, respectively.

// using new statement

var myObject:Object = new Object({propA:1, propB:2, propC:3});

// assigning literal directly

var myObject:Object = {propA:1, propB:2, propC:3};

Do not confuse a string literal with a String object. In the following example, the first line of code creates the string literal firstStr, and the second line of code creates the String object secondStr:

var firstStr:String = "foo"

var secondStr:String = new String("foo")

Use string literals unless you specifically need to use a String object for better performance.

 

About comments

TOP

Comments are a way of annotating your code with plain-English descriptions that do not get evaluated by the compiler. You can use comments within your code to describe what the code is doing or to describe which data returns to the document. Using comments can help you remember important coding decisions, and it can be helpful to anyone else who reads your code. Comments must clearly explain the intent of the code and not just translate the code. If something is not readily obvious in the code, you should add comments to it.

Using comments to add notes to scripts is highly recommended. Comments document the decisions you make in the code, answering both how and why. They make ActionScript easier to understand. For example, you might describe a work-around in comments. Therefore, you or another developer can easily find sections of code to update or fix. Or, if the issue is fixed or improved in a future version of Flash or Flash Player, you could improve the ActionScript by removing the work-around.

Avoid using cluttered comments. An example of cluttered comments is a line of equal signs (=) or asterisks (*) used to create a block or separation around your comments. Instead, use white space to separate your comments from the ActionScript. If you format your ActionScript using the Auto Format button in the Actions panel or Script window, this removes the white space. Remember to add white space back into your code, or use single comment lines (//) to maintain spacing; these lines are easier to remove after you format your code than trying to determine where white space once was.

Before you deploy your project, remove any superfluous comments from the code, such as "define the x and y variables" or other comments that are immediately obvious to other developers. If you find that you have many extra comments in the ActionScript, consider whether you need to rewrite some of the code. If you need to include many comments about how the code works, it is usually a sign that the ActionScript is inelegant and not intuitive.

When you enable syntax coloring, comments are gray by default. Comments can be any length without affecting the size of the exported file, and they do not need to follow rules for ActionScript syntax or keywords.

NOTE : Using comments is most important in ActionScript that is intended to teach an audience. Add comments to your code if you are creating sample applications for the purpose of teaching Flash or if you are writing articles or tutorials on ActionScript.

 

Single-line comments

TOP

You use single-line comments to add a comment to a single line in your code. You might comment out a single line of code, or add a short description of what a piece of code accomplishes. To indicate that a line or portion of a line is a comment, precede the comment with two forward slashes (//), as shown in the following code:

// The following sets a local variable for age.
var myAge:Number = 26;

Single-line comments are typically used to explain a small code snippet. You can use single-line comments for any short comments that fit on a single line. The following example includes a single-line comment:

while (condition) {
// handle condition with statements
}

 

Multiline comments

TOP

Use multiline comments, also called block comments, for comments that are several lines in length. Developers commonly use multiline comments to describe files, data structures, methods, and descriptions of files. They are usually placed at the beginning of a file and before or within a method.

To create a comment block, place /* at the beginning of the commented lines and */ at the end of the comment block. This technique lets you create lengthy comments without adding // at the beginning of each line. Using // for numerous sequential lines can lead to some problems when you modify the comments.

The format for a multiline comment is as follows.

/*

The following ActionScript initializes variables used in the main and sub-menu systems. Variables are used to track what options are clicked.

*/

TIP : If you place the comment characters (/* and */) on separate lines at the beginning and end of the comment, you can easily comment them out by placing double slash characters (//) in front of them (for example, ///* and //*/). These let you quickly and easily comment and uncomment your code.

By placing large chunks of script in a comment block, called commenting out a portion of your script, you can test specific parts of a script. For example, when the following script runs, none of the code in the comment block executes:

// The following code runs.

var x:Number = 15;

var y:Number = 20;

// The following code is commented out and will not run.

/*

// create new Date object

var myDate:Date = new Date();

var currentMonth:Number = myDate.getMonth();

// convert month number to month name

var monthName:String = calcMonth(currentMonth);

var year:Number = myDate.getFullYear();

var currentDate:Number = myDate.getDate();

*/

// The code below runs.

var namePrefix:String = "My name is";

var age:Number = 20;

TIP : It's good practice to place a blank line before a block comment.

 

Trailing comments

TOP

You use trailing comments to add a comment on the same line as your code. These comments appear on the same line as your ActionScript code. Developers commonly use trailing comments to indicate what a variable contains or to describe or note the value that returns from a line of ActionScript. Format trailing comments as follows:

var myAge:Number = 26; // variable for my age

trace(myAge); // 26

Space the comments to the right so readers can distinguish them from the code. Try to have the comments line up with each other, if possible, as shown in the following code.

var myAge:Number = 28; // my age

var myCountry:String = "Canada"; // my country

var myCoffee:String = "Hortons"; // my coffee preference

If you use autoformatting (click the Auto Format button in the Actions panel), trailing comments move to the next line. Add these comments after you format your code, or you must modify their placement after using the Auto Format button.

 

Comments inside classes

TOP

You use comments in your classes and interfaces to document them to help developers understand the contents of your class. You might start all your class files with a comment that provides the class name, its version number, the date, and your copyright. For example, you might create documentation for your class that is similar to the following comment:

/**

Pelican class

version 1.2

10/10/2005

copyright Macromedia, Inc.

*/

Use block comments to describe files, data structures, methods, and descriptions of files. They are usually placed at the beginning of a file and before or within a method.

There are two kinds of comments in a typical class or interface file: documentation comments and implementation comments. Documentation comments are used to describe the code's specifications and do not describe the implementation. You use documentation comments to describe interfaces, classes, methods, and constructors. Implementation comments are used to comment out code or to comment on the implementation of particular sections of code.

Include one documentation comment per class, interface, or member, and place it directly before the declaration. If you have additional information to document that does not fit into the documentation comments, use implementation comments (in the format of block comments or single-line comments). Implementation comments directly follow the declaration.

The two kinds of comments use slightly different delimiters. Documentation comments are delimited with /** and */, and implementation comments are delimited with /* and */.

TIP : Don't include comments that do not directly relate to the class being read. For example, do not include comments that describe the corresponding package.

 

About constants and keywords

TOP

Constants and keywords are the backbone of ActionScript syntax. Constants are properties with a fixed value that cannot be altered, so they are values that don't change throughout an application.

Flash includes several predefined constants, which can help simplify application development. An example of constants can be found in the Key class, which includes many properties, such as Key.ENTER or Key.PGDN. If you rely on constants, you never have to remember that the key code values for the Enter and Page Down keys are 13 and 34. Using constant values not only makes development and debugging easier, but it also makes your code easier to read by your fellow developers.

Keywords in ActionScript are used to perform specific kinds of actions. They are also reserved words because of this, so you can't use them as identifiers (such as variable, function, or label names). Examples of some reserved keywords are if, else, this, function, and return.

 

Using constants

TOP

Constants are properties with a fixed value that cannot be altered; in other words, they are values that don't change throughout an application. The ActionScript language contains many predefined constants. For example, the constants BACKSPACE, ENTER, SPACE, and TAB are properties of the Key class and refer to keyboard keys. The constant Key.TAB always has the same meaning: it indicates the Tab key on a keyboard. Constants are useful for comparing values and for using values in your application that do not change.

To test whether the user is pressing the Enter key, you could use the following statement:

var keyListener:Object = new Object();

keyListener.onKeyDown = function() {

if (Key.getCode() == Key.ENTER) {

trace("Are you ready to play?");

}

};

Key.addListener(keyListener);

For the previous ActionScript to work, it may be necessary to disable keyboard shortcuts in the authoring environment. Select Control > Test Movie from the main menu, then while previewing the SWF file in the player, select Control > Disable Keyboard Shortcuts from the SWF file's preview window.

In Flash there is no way to create your own constant values except when you create your own custom classes with private member variables. You cannot create a "read-only" variable within Flash.

Variables should be lowercase or mixed-case letters; however, constants (variables that do not change) should be uppercase. Separate words with underscores, as the following ActionScript shows:

var BASE_URL:String = "http://www.macromedia.com"; //constant

var MAX_WIDTH:Number = 10;               //constant

Write static constants in uppercase, and separate words with an underscore. Do not directly code numerical constants unless the constant is 1, 0, or -1, which you might use in a for loop as a counter value.

You can use constants for situations in which you need to refer to a property whose value never changes. This helps you find typographical mistakes in your code that you might not find if you use literals. It also lets you change the value in a single place.

For example, the class definition in the next example creates three constants that follow the naming convention used by ActionScript 2.0.

To use constants in an application:

  1. Select File > New and then select ActionScript File to create an AS file.

  2. Name the new file ConstExample.as.

  3. Type the following code into the Script window:

    class ConstExample {

    public static var EXAMPLE_STATIC:String = "Global access";

    public var EXAMPLE_PUBLIC:String = "Public access";

    private var EXAMPLE_PRIVATE:String = "Class access";

    }

    The EXAMPLE_STATIC property is a static property, which means that the property applies to the class as a whole instead of to a particular instance of the class. You must access a static property of a class using the name of the class instead of the name of an instance. You cannot access a static property through a class instance.

  4. Create a new Flash document and save it as const.fla.

  5. Open the Actions panel, and type the following code on Frame 1 of the Timeline:

    trace(ConstExample.EXAMPLE_STATIC); // output: Global access

    When you declare the EXAMPLE_STATIC property as static, you use this code to access the value of the property.

  6. Select Control > Test Movie to test your document.

    You will see Global access in the Output panel.

  7. In the Actions panel, type this code following the code you added in step 5.

    trace(ConstExample.EXAMPLE_PUBLIC); // error

    trace(ConstExample.EXAMPLE_PRIVATE); // error

  8. Select Control > Test Movie to test your document.

    The EXAMPLE_PUBLIC and EXAMPLE_PRIVATE properties are not static properties. When you try to access the values through the class, you see the error message:

    The property being referenced does not have the static attribute.

    To access a property that is not static, you must access the value through an instance of the class. Because the EXAMPLE_PUBLIC property is a public property, it is available to code outside of the class definition.

  9. In the Actions panel, delete the trace statements that you added in steps 5 and 7.

  10. Type the following code into the Actions panel:

    var myExample:ConstExample = new ConstExample();

    trace(myExample.EXAMPLE_PUBLIC); // output: Public access

    This code instantiates the myExample instance and accesses the EXAMPLE_PUBLIC property.

  11. Select Control > Test Movie to test your document.

    You see Public access in the Output panel.

  12. In the Actions panel, delete the trace statement that you added in step 10.

    Type the following code into the Actions panel.

    trace(myExample.EXAMPLE_PRIVATE); // error

  13. The EXAMPLE_PRIVATE property is a private property, so it is available only within the class definition.

  14. Select Control > Test Movie to test your document.

    You see The member is private and cannot be accessed in the Output panel.

 

Using variables in an application

TOP

About keywords

Keywords are words in ActionScript that do one specific thing. For example, you use the var keyword to declare a variable. The var keyword is shown in the following line of code:

var myAge:Number = 26;

A keyword is a reserved word that has a specific meaning: for example, you use the class keyword to define new a new ActionScript class; and you use the var keyword to declare local variables. Other examples of reserved keywords are: if, else, this, function, and return.

Keywords cannot be used as identifiers (such as variable, function, or label names), and you should not use them elsewhere in your FLA files for other things (such as instance names). You have already used the var keyword a lot, particularly if you read Data and Data Types. ActionScript reserves words in the language for specific use. Therefore, you can't use keywords as identifiers (such as variable, function, or label names).

 

About keywords

TOP

Keywords are words in ActionScript that do one specific thing. For example, you use the var keyword to declare a variable. The var keyword is shown in the following line of code:

var myAge:Number = 26;

A keyword is a reserved word that has a specific meaning: for example, you use the class keyword to define new a new ActionScript class; and you use the var keyword to declare local variables. Other examples of reserved keywords are: if, else, this, function, and return.

Keywords cannot be used as identifiers (such as variable, function, or label names), and you should not use them elsewhere in your FLA files for other things (such as instance names). You have already used the var keyword a lot, particularly if you read Data and Data Types. ActionScript reserves words in the language for specific use. Therefore, you can't use keywords as identifiers (such as variable, function, or label names).

add

and

break

case

catch

class

continue

default

delete

do

dynamic

else

eq

extends

finally

for

function

ge

get

gt

if

ifFrameLoaded

implements

import

in

instanceof

interface

intrinsic

le

lt

ne

new

not

on

onClipEvent

or

private

public

return

set

static

switch

tellTarget

this

throw

try

typeof

var

void

while

with

 

The following table lists keywords that are reserved for future use by ActionScript or the ECMAScript (ECMA-262) edition 4 draft language specification. You should also avoid using these keywords in your code:

abstract

enum

export

short

byte

long

synchronized

char

debugger

protected

double

volatile

float

throws

transient

goto

All built-in class names, component class names, and interface names are reserved words, and should not be used as identifiers in your code:

Accessibility

Accordion

Alert

Array

Binding

Boolean

Button

Camera

CellRenderer

CheckBox

Collection

Color

ComboBox

ComponentMixins

ContextMenu

ContextMenuItem

CustomActions

CustomFormatter

CustomValidator

DataGrid

DataHolder

DataProvider

DataSet

DataType

Date

DateChooser

DateField

Delta

DeltaItem

DeltaPacket

DepthManager

EndPoint

Error

FocusManager

Form

Function

Iterator

Key

Label

List

Loader

LoadVars

LocalConnection

Log

Math

Media

Menu

MenuBar

Microphone

Mouse

MovieClip

MovieClipLoader

NetConnection

NetStream

Number

NumericStepper

Object

PendingCall

PopUpManager

PrintJob

ProgressBar

RadioButton

RDBMSResolver

Screen

ScrollPane

Selection

SharedObject

Slide

SOAPCall

Sound

Stage

String

StyleManager

System

TextArea

TextField

TextFormat

TextInput

TextSnapshot

TransferObject

Tree

TreeDataProvider

TypedValue

UIComponent

UIEventDispatcher

UIObject

Video

WebService

WebServiceConnector

Window

XML

XMLConnector

XUpdateResolver

Several words, although they are not reserved words, should not be used as identifiers (such as variable or instance names) in your ActionScript code. These are words that are used by the built-in classes that make up the ActionScript language. Therefore, do not use the names of properties, methods, classes, interfaces, component class names, and values as names in your code (such as when you name variables, classes, or instances).

 

About statements

TOP

A statement is an instruction you give the FLA file to do something, such as to perform a particular action. For example, you can use a conditional statement to determine whether something is true or exists. Then your code might execute actions that you specify, such as functions or expressions, based on whether the condition is true or not.

For example, the if statement is a conditional statement and evaluates a condition to determine the next action that should occur in your code.

// if statement

if (condition) {

// statements;

}

Another example is the return statement, which returns a result as a value of the function in which it executes.

There are many different ways for you to format or write ActionScript. You might differ from someone else who writes ActionScript in the way you form syntax, such as the way you space out your statements or where you put curly braces ({}) in your code. Even though there are several different ways you can form statements without breaking your code, there are some general guidelines you can follow to write well-formed ActionScript.

Place only one statement on a line to increase the readability of your ActionScript. The following example shows the recommended and not recommended statement usage:

theNum++; // recommended

theOtherNum++; // recommended

aNum++; anOtherNum++; // not recommended

Assign variables as separate statements. Consider the following ActionScript example:

var myNum:Number = (a = b + c) + d;

This ActionScript embeds an assignment within the code, which is difficult to read. If you assign variables as separate statements, it improves readability, as the following example shows:

var a:Number = b + c;

var myNum:Number = a + d;

The following sections show you how to form specific statements in ActionScript.

 

About compound statements

TOP

A compound statement contains numerous statements that you enclose within curly brace ({}) punctuators. The statements inside a compound statement can be any kind of ActionScript statement. A typical compound statement is shown below.

The statements within the curly brace punctuators are indented from the compound statement, as the following ActionScript shows:

var a:Number = 10;

var b:Number = 10;

if (a == b) {

// This code is indented.

trace("a == b");

trace(a);

trace(b);

}

This compound statement contains several statements, but acts like a single statement in your ActionScript code. The opening brace is placed at the end of the compound statement. The closing brace begins a line, and aligns with the beginning of the compound statement.

 

About conditions

TOP

You use conditions to determine whether something is true or exists, and then you can optionally repeat an action (using loops), or execute actions that you specify, such as functions or expressions, based on whether the condition is true or not. For example, you can determine whether a certain variable is defined or has a certain value and execute a block of code based on the result. Also, you could change the graphics within your Flash document based on what time the user's system clock is set to or on the weather in the user's current location.

To perform an action depending on whether a condition exists, or to repeat an action (create loop statements), you can use if, else, else if, for, while, do while, for..in, or switch statements.

 

About writing conditions

TOP

Statements that check whether a condition is true or false begin with the term if. If the condition evaluates to true, ActionScript executes the next statement. If the condition evaluates to false, ActionScript skips to the next statement outside the block of code.

TIP : To optimize your code's performance, check for the most likely conditions first.

The following statements test three conditions. The term else if specifies alternative tests to perform if previous conditions are false.

if ((passwordTxt.text.length == 0) || (emailTxt.text.length == 0)) {

gotoAndStop("invalidLogin");

} else if (passwordTxt.text == userID){

gotoAndPlay("startProgram");

}

In this code snippet, if the length of the passwordTxt or emailTxt text fields is 0 (for example, the user hasn't entered a value), the Flash document redirects to the invalidLogin frame label.

If both the passwordTxt and emailTxt text fields contain values and the passwordTxt text field's contents match the userID variable, the SWF file redirects to the startProgram frame label.

If you want to check for one of several conditions, you can use the switch statement rather than multiple else if statements.

 

Using the if statement

TOP

Use the if statement when you want to execute a series of statements based on a whether a certain condition is true.

// if statement

if (condition) {

// statements;

}

There are several times when you'll use if statements when you work on a Flash project. For example, if you are building a Flash site that requires users to log in before they can access certain sections of a website, you can use an if statement to validate that the user enters some text in the username and password fields.

If you need to validate user names and passwords using an external database, you probably want to verify that the username/password combination a user submits matches a record in the database. You also want to check whether the user has permission to access the specified part of the site.

If you script animations in Flash, you might want to use the if statement to test whether an instance on the Stage is still within the boundaries of the Stage. For example, if a ball moves downward along the y-axis, you might need to detect when the ball collides with the bottom edge of the Stage, so you can change the direction so that the ball appears to bounce upwards.

To use an if statement:

  1. Select File > New and then select Flash Document.

  2. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:

    // create a string to hold AM and PM

    var amPm:String = "AM";

    // no parameters pass to Date, so returns current date/time

    var current_date:Date = new Date();

    // if current hour is greater than/equal to 12, sets amPm string to "PM".

    if (current_date.getHours() >= 12) {

    amPm = "PM";

    }

    trace(amPm);

  3. Select Control > Test Movie to test the ActionScript.

    In this code, you create a string that holds AM or PM based on the current time of day. If the current hour is greater than or equal to 12 the amPM string sets to PM. Finally, you trace the amPm string, and if the hour is greater than or equal to 12, PM is displayed. Otherwise, you'll see AM.

 

Using the if..else statement

TOP

The if..else conditional statement lets you test a condition and then execute a block of code if that condition exists or execute an alternative block of code if the condition does not exist.
For example, the following code tests whether the value of x exceeds 20, generates a trace() statement if it does, or generates a different trace() statement if it does not:

if (x > 20) {

trace("x is > 20");

} else {

trace("x is <= 20");

}

If you do not want to execute an alternative block of code, you can use the if statement without the else statement.

The if..else statement in Flash is similar to the if statement. For example, if you use the if statement to validate that a user's supplied user name and password matches a value stored in a database, then you might want to redirect the user based on whether the user name and password are correct. If the login is valid, you can redirect the user to a welcome page using the if block. However, if the login was invalid, you can redirect the user to the login form and display an error message using the else block.

To use an if..else statement in a document:

  1. Select File > New and then select Flash Document to create a new FLA file.

  2. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:

    // create a string that holds AM/PM based on the time of day.

    var amPm:String;

    // no parameters pass to Date, so returns current date/time.

    var current_date:Date = new Date();

    // if current hour is greater than/equal to 12, sets amPm string to "PM".

    if (current_date.getHours() >= 12) {

    amPm = "PM";

    } else {

    amPm = "AM";

    }

    trace(amPm);

  3. Select Control > Test Movie to test the ActionScript.

    In this code, you create a string that holds AM or PM based on the current time of day. If the current hour is greater than or equal to 12, the amPM string sets to PM. Finally, you trace the amPm string, and if the hour is greater than or equal to 12, PM is displayed. Otherwise, you'll see AM in the Output panel.

 

Using the if..else if statement

TOP

You can test for more than one condition using the if..else if conditional statement. You use the following syntax in an if..else if statement:

// else-if statement

if (condition) {

// statements;

} else if (condition) {

// statements;

} else {

// statements;

}

You want to use an if..else if block in your Flash projects when you need to check a series of conditions. For example, if you want to display a different image on the screen based on the time of the day the user is visiting, you can create a series of if statements that determine if it's early morning, afternoon, evening, or night time. Then you can display an appropriate graphic.

The following code not only tests whether the value of x exceeds 20 but also tests whether the value of x is negative:

if (x > 20) {

trace("x is > 20");

} else if (x < 0) {

trace("x is negative");

}

To use an if..else if statement in a document:

  1. Select File > New and then select Flash Document.

  2. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:

    var now_date:Date = new Date();

    var currentHour:Number = now_date.getHours();

    // if the current hour is less than 11AM...

    if (currentHour < 11) {

    trace("Good morning");

    // else..if the current hour is less than 3PM...

    } else if (currentHour < 15) {

    trace("Good afternoon");

    // else..if the current hour is less than 8PM...

    } else if (currentHour < 20) {

    trace("Good evening");

    // else the current hour is between 8PM and 11:59PM

    } else {

    trace("Good night");

    }

  3. Select Control > Test Movie to test the ActionScript.

    In this code, you create a string called currentHour that holds the current hour number (for example, if it's 6:19 pm, currentHour holds the number 18). You use the getHours() method of the Date class to get the current hour. Then you can use the if..else if statement to trace information to the Output panel, based on the number that returns. For more information, see the comments in the previous code snippet.

 

Using a switch statement

TOP

The switch statement creates a branching structure for ActionScript statements. Similar to the if statement, the switch statement tests a condition and executes statements if the condition returns a value of true.

When you use a switch statement, the break statement instructs Flash to skip the rest of the statements in that case block and jump to the first statement that follows the enclosing switch statement. If a case block doesn't contain a break statement, a condition called "fall through" occurs. In this situation, the following case statement also executes until a break statement is encountered or the switch statement ends. This behavior is demonstrated in the following example, where the first case statement doesn't contain a break statement and therefore both of the code blocks for the first two cases (A and B) execute.

All switch statements should include a default case. The default case should always be the last case on a switch statement and should also include a break statement to prevent a fall-through error if another case is added. For example, if the condition in the following example evaluates to A, both the statements for case A and B execute, because case A lacks a break statement. When a case falls through, it does not have a break statement, but includes a comment in the break statement's place, which you can see in the following example after case A. Use the following format when you write switch statements:

switch (condition) {

case A :

// statements

// falls through

case B :

// statements

break;

case Z :

// statements

break;

default :

// statements

break;

}

To use a switch statement in a document:

  1. Select File > New and then select Flash Document.

  2. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:

    var listenerObj:Object = new Object();

    listenerObj.onKeyDown = function() {

    // Use the String.fromCharCode() method to return a string.

    switch (String.fromCharCode(Key.getAscii())) {

    case "A" :

    trace("you pressed A");

    break;

    case "a" :

    trace("you pressed a");

    break;

    case "E" :

    case "e" :

    /* E doesn't have a break statement, so this block executes if you press e or E. */

    trace("you pressed E or e");

    break;

    case "I" :

    case "i" :

    trace("you pressed I or i");

    break;

    default :

    /* If the key pressed isn't caught by any of the above cases, execute the default case here. */

    trace("you pressed some other key");

    }

    };

    Key.addListener(listenerObj);

  3. Select Control > Test Movie to test the ActionScript.

    Type letters using the keyboard, including the a, e, or i key. When you type those three keys, you'll see the trace statements in the preceding ActionScript. The line of code creates a new object that you use as a listener for the Key class. You use this object to notify the onKeyDown() event when the user presses a key. The Key.getAscii() method returns the ASCII code of the last key that the user presses or releases, so you need to use the String.fromCharCode() method to return a string that contains the characters represented by the ASCII values in the parameters. Because "E" doesn't have a break statement, the block executes if the user presses the e or E key. If the user presses a key that isn't caught by any of the first three cases, the default case executes.

 

Using try..catch and try..catch..finally statements

TOP

Using try..catch..finally blocks lets you add error handling to your Flash applications. The try..catch..finally keywords let you enclose a block of code where an error can occur and respond to that error. If any code within the try code block throws an error (using the throw statement), control passes to the catch block, if one exists. Then control passes to the finally code block, if one exists. The optional finally block always executes, regardless of whether an error was thrown.

If code within the try block doesn't throw an error (that is, the try block completes normally), the code in the finally block still executes.

NOTE : The finally block executes even if the try block exits using a return statement

You write try..catch and try..catch..finally statements using the following format:

// try-catch

try {

// statements

} catch (myError) {

// statements

}

// try-catch-finally

try {

// statements

} catch (myError) {

// statements

} finally {

// statements

}

Any time your code throws an error, you can write custom handlers to handle the error gracefully and take appropriate actions. You might need to try loading external data from a web service or text file or to display an error message to the end user. You can even use the catch block to try to connect to a web service that alerts an administrator that a particular error occurred, so he or she can make sure the application works properly.

To use the try..catch..finally block for data validation before dividing some numbers:

  1. Select File > New and then select Flash Document.

  2. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:

    var n1:Number = 7;

    var n2:Number = 0;

    try {

    if (n2 == 0) {

    throw new Error("Unable to divide by zero");

    }

    trace(n1/n2);

    } catch (err:Error) {

    trace("ERROR! " + err.toString());

    } finally {

    delete n1;

    delete n2;

    }

  3. Select Control > Test Movie to test the document.

  4. The Output panel displays Unable to divide by zero.

  5. Return to the authoring environment and change the following line of code:

    var n2:Number = 0;

    to

    var n2:Number = 2;

  6. Select Control > Enter to test the document again.

    If the value of n2 equals zero, an error is thrown and is caught by the catch block, which displays a message in the Output panel. If the value of y is not equal to zero, the Output panel displays the result of n1 divided by n2. The finally block executes regardless of whether an error occurs and deletes the values of the n1 and n2 variables from the Flash document.

You aren't limited to throwing new instances of the Error class when an error occurs. You could also extend the Error class to create your own custom errors, as demonstrated in the following example.

To create a custom error:

  1. Select File > New and create a new ActionScript file.

  2. Select File > Save As and name the file DivideByZeroException.as.

  3. Type the following ActionScript into the Script pane:

    // In DivideByZeroException.as:

    class DivideByZeroException extends Error {

    var message:String = "Divide By Zero error";

    }

  4. Save the ActionScript file.

  5. Create a new Flash document named exception_test.fla in the same directory as the ActionScript file, and then save the file.

  6. Type the following ActionScript into the Actions panel in Frame 1 of the main Timeline:

    var n1:Number = 7;

    var n2:Number = 0;

    try {

    if (n2 == 0) {

    throw new DivideByZeroException();

    } else if (n2 < 0) {

    throw new Error("n2 cannot be less than zero");

    } else {

    trace(n1/n2);

    }

    } catch (err:DivideByZeroException) {

    trace(err.toString());

    } catch (err:Error) {

    trace("An unknown error occurred; " + err.toString());

    }

  7. Save the Flash document and select Control > Test Movie to test the file in the test environment.

Because the value of n2 equals 0, Flash throws your custom DivideByZeroException error class and displays Divide By Zero error in the Output panel. If you change the value of n2 in line two from 0 to -1, and retest the Flash document, you would see An unknown error occurred; n2 cannot be less than zero in the Output panel. Setting the value of n2 to any number greater than 0 causes the result of the division to appear in the Output panel.

 

About the conditional operator and alternative syntax

TOP

If you like shortcuts, you can use the conditional (?:) operator, also called conditional expressions. The conditional operator lets you convert simple if..else statements into a single line of code. The operator helps decrease the amount of code you write while accomplishing the same thing, but it also tends to make your ActionScript more difficult to read.

The following condition is written in long hand, and checks whether the variable numTwo is greater than zero, and returns the result of numOne/numTwo or a string of carrot:

var numOne:Number = 8;

var numTwo:Number = 5;

if (numTwo > 0) {

trace(numOne / numTwo); // 1.6

} else {

trace("carrot");

}

Using a conditional expression, you would write the same code using this format:

var numOne:Number = 8;

var numTwo:Number = 0;

trace((numTwo > 0) ? numOne/numTwo : "carrot");

As you can see, the shortened syntax reduces readability, and so it is not preferable. If you must use conditional operators, place the leading condition (before the question mark [?]) inside parentheses. This helps improve the readability of your ActionScript. The following code is an example of ActionScript with improved readability:

var numOne:Number;

(numOne >= 5) ? numOne : -numOne;

You can write a conditional statement that returns a Boolean value, as the following example shows:

if (cartArr.length > 0) {

return true;

} else {

return false;

}

However, compared with the previous code, the ActionScript in the following example is preferable:

return (cartArr.length > 0);

The second snippet is shorter and has fewer expressions to evaluate. It's easier to read and understand.

When you write complex conditions, it is good form to use parentheses [()] to group conditions. If you do not use parentheses, you (or others working with your ActionScript) might run into operator precedence errors.

For example, the following code does not use parentheses around the condition:

if (fruit == "apple" && veggie == "leek") {}

The following code uses good form by adding parentheses around conditions:

if ((fruit == "apple") && (veggie == "leek")) {}

 

Repeating actions using loops

TOP

ActionScript can repeat an action a specified number of times or while a specific condition exists. Loops let you repeat a series of statements when a particular condition is true. There are four types of loops in ActionScript: for loops, for..in loops, while loops, and do..while loops. Each type of loop behaves somewhat differently, and each one is useful for different purposes.

Most loops use some kind of counter to control how many times the loop executes. Each execution of a loop is called an iteration. You can declare a variable and write a statement that increases or decreases the variable each time the loop executes. In the for action, the counter and the statement that increments the counter are part of the action.

Loop

Description

for loops

Repeat an action using a built-in counter.

for..in loops

Iterate over the children of a movie clip or object.

while loops

Repeat an action while a condition exists.

do..while loops

Similar to while loops, except the expression evaluates at the bottom of the code block, so the loop always runs at least once.

The most common type of loop is the for loop, which loops over a block of code a predefined number of times. For example, if you have an array of items, and you want to perform a series of statements on each item in the array, you would use a for loop and loop from 0 to the number of items in the array. Another type of loop is the for..in loop, which can be very useful when you want to loop over each name/value pair within an object and then perform some type of action. This can be very useful when you are debugging your Flash projects and want to display the values that load from external sources, such as web services or external text/XML files. The final two types of loops (while and do..while) are useful when you want to loop over a series of statements but you don't necessarily know how many times you need to loop. In this case you can use a while loop that loops as long as a certain condition is true.

ActionScript can repeat an action a specified number of times or while a specific condition exists. Use the while, do..while, for, and for..in actions to create loops. This section contains general information on these loops. See the following procedures for more information on each of these loops.

To repeat an action while a condition exists:

Use the while statement.

A while loop evaluates an expression and executes the code in the body of the loop if the expression is true. After each statement in the body is executed, the expression is evaluated again.

In the following example, the loop executes four times:

var i:Number = 4;

while (i > 0) {

myClip.duplicateMovieClip("newMC" + i, i, {_x:i*20, _y:i*20});

i--;

}

You can use the do..while statement to create the same kind of loop as a while loop. In a do..while loop, the expression is evaluated at the bottom of the code block so that the loop always runs at least once.

This is shown in the following example:

var i:Number = 4;

do {

myClip.duplicateMovieClip("newMC" + i, i, {_x:i*20, _y:i*20});

i--;

} while (i > 0);

To repeat an action using a built-in counter:

  • Use the for statement.

    Most loops use some kind of counter to control how many times the loop executes. Each execution of a loop is called an iteration. You can declare a variable and write a statement that increases or decreases the variable each time the loop executes. In the for action, the counter and the statement that increments the counter are part of the action.

    In the following example, the first expression (var i:Number = 4) is the initial expression that is evaluated before the first iteration. The second expression (i > 0) is the condition that is checked each time before the loop runs. The third expression (i--) is called the post expression and is evaluated each time after the loop runs.

    for (var i:Number = 4; i > 0; i--) {

    myClip.duplicateMovieClip("newMC" + i, i, {_x:i*20, _y:i*20});

    }

To loop through the children of a movie clip or an object:

  • Use the for..in statement.

    Children include other movie clips, functions, objects, and variables. The following example uses the trace statement to print its results in the Output panel:

    var myObject:Object = {name:'Joe', age:25, city:'San Francisco'};

    var propertyName:String;

    for (propertyName in myObject) {

    trace("myObject has the property: " + propertyName + ", with the value: " + myObject[propertyName]);

    }

    This example produces the following results in the Output panel:

    myObject has the property: name, with the value: Joe

    myObject has the property: age, with the value: 25

    myObject has the property: city, with the value: San Francisco

    You might want your script to iterate over a particular type of child--for example, over only movie clip children. You can do this using for..in with the typeof operator. In the following example, a child movie clip instance (called instance2) is inside a movie clip instance on the Stage. Add the following ActionScript to Frame 1 of the Timeline:

    for (var myName in this) {

    if (typeof (this[myName]) == "movieclip") {

    trace("I have a movie clip child named " + myName);

    }

    }

 

About creating and ending loops

TOP

The following example shows a simple array of month names. A for loop iterates from 0 to the number of items in the array and displays each item in the Output panel.

var monthArr:Array = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

var i:Number;

for (i = 0; i < monthArr.length; i++) {

trace(monthArr[i]);

}

When you work with arrays, whether they're simple or complex, you need to be aware of a condition called an infinite loop. An infinite loop, as its name suggests, is a loop with no end condition. This causes real problems--crashing your Flash application, causing your Flash document to stop responding in a web browser, or causing very inconsistent behavior of your Flash document. The following code is an example of an infinite loop:

// BAD CODE- creates an infinite loop

// USE AT OWN RISK!

var i:Number;

for (i = 0; i < 10; i--) {

trace(i);

}

The value of i is initialized to 0 and the end condition is met when i is greater than or equal to 10 and after each iteration the value of i is decremented. You can probably see the obvious error immediately: if the value of i decreases after each loop iteration, the end condition is never met. The results vary on each computer you run it on, and the speed at which the code fails depends on the speed of the CPU and other factors. For example, the loop executes about 142,620 times before displaying an error message on a given computer.

The following error message is displayed in a dialog box:

A script in this movie is causing Flash Player to run slowly. If it continues to run, your computer may become unresponsive. Do you want to abort the script?

When you work with loops (and especially while and do..while loops), always make sure that the loop can exit properly and does not end up in an infinite loop.

 

About casting objects

TOP

The syntax for casting is type(item), where you want the compiler to behave as if the data type of the item is type. Casting is essentially a function call, and the function call returns null if the cast fails at runtime (this occurs in files published for Flash Player 7 or later; files published for Flash Player 6 do not have runtime support for failed casts). If the cast succeeds, the function call returns the original object. However, the compiler cannot determine whether a cast will fail at runtime and won't generate compile-time errors in those cases.

The following code shows an example:

// Both the Cat and Dog classes are subclasses of the Animal class

function bark(myAnimal:Animal) {

var foo:Dog = Dog(myAnimal);

foo.bark();

}

var curAnimal:Animal = new Dog();

bark(curAnimal); // Will work

curAnimal = new Cat();

bark(curAnimal); // Won't work

In this example, you asserted to the compiler that foo is a Dog object, and therefore the compiler assumes that foo.bark(); is a legal statement. However, the compiler doesn't know that the cast will fail (that is, that you tried to cast a Cat object to an Animal type), so no compile-time error occurs. However, if you include a check in your script to make sure that the cast succeeds, you can find casting errors at runtime, as shown in the following example.

function bark(myAnimal:Animal) {

var foo:Dog = Dog(myAnimal);

if (foo) {

foo.bark();

}

}

You can cast an expression to an interface. If the expression is an object that implements the interface or has a base class that implements the interface, the cast succeeds. If not, the cast fails.

NOTE : Casting to null or undefined returns undefined.

You can't override primitive data types that have a corresponding global conversion function with a cast operator of the same name. This is because the global conversion functions have precedence over the cast operators. For example, you can't cast to Array because the Array() conversion function takes precedence over the cast operator.

This example defines two string variables (firstNum and secondNum), which are added together. The initial result is that the numbers are concatenated instead of added because they are a String data type. The second trace statement converts both numbers to a Number data type before performing the addition that yields the proper result. Data conversion is important when working with data loaded using XML or FlashVars, as shown in the following example:

var firstNum:String = "17";
var secondNum:String = "29";
trace(firstNum + secondNum); // 1729
trace(Number(firstNum) + Number(secondNum)); // 46

About creating and ending loops

TOP

The following example shows a simple array of month names. A for loop iterates from 0 to the number of items in the array and displays each item in the Output panel.

var monthArr:Array = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

var i:Number;

for (i = 0; i < monthArr.length; i++) {

trace(monthArr[i]);

}

When you work with arrays, whether they're simple or complex, you need to be aware of a condition called an infinite loop. An infinite loop, as its name suggests, is a loop with no end condition. This causes real problems--crashing your Flash application, causing your Flash document to stop responding in a web browser, or causing very inconsistent behavior of your Flash document. The following code is an example of an infinite loop:

// BAD CODE- creates an infinite loop

// USE AT OWN RISK!

var i:Number;

for (i = 0; i < 10; i--) {

trace(i);

}

The value of i is initialized to 0 and the end condition is met when i is greater than or equal to 10 and after each iteration the value of i is decremented. You can probably see the obvious error immediately: if the value of i decreases after each loop iteration, the end condition is never met. The results vary on each computer you run it on, and the speed at which the code fails depends on the speed of the CPU and other factors. For example, the loop executes about 142,620 times before displaying an error message on a given computer.

The following error message is displayed in a dialog box:

A script in this movie is causing Flash Player to run slowly. If it continues to run, your computer may become unresponsive. Do you want to abort the script?

When you work with loops (and especially while and do..while loops), always make sure that the loop can exit properly and does not end up in an infinite loop.

 

Using for loops

TOP

The for loop lets you iterate over a variable for a specific range of values. A for loop is useful when you know exactly how many times you need to repeat a series of ActionScript statements. This can be useful if you want to duplicate a movie clip on the Stage a certain number of times or to loop over an array and perform a task on each item in that array. A for loop repeats an action using a built-in counter. In a for statement, the counter and the statement that increments the counter are all part of the for statement. You write the for statement using the following basic format:

for (init; condition; update) {

// statements;

}

You must supply three expressions to a for statement: a variable that is set to an initial value, a conditional statement that determines when the looping ends, and an expression that changes the value of the variable with each loop. For example, the following code loops five times. The value of the variable i starts at 0 and ends at 4, and the output are the numbers 0 through 4, each on its own line.

var i:Number;

for (i = 0; i < 5; i++) {

trace(i);

}

In the next example, the first expression (i = 0) is the initial expression that evaluates before the first iteration. The second expression (i < 5) is the condition that you check each time before the loop runs. The third expression (i++) is called the post expression and is evaluated each time after the loop runs.

To create a for loop:

  1. Select File > New and then select Flash Document.

  2. Create a movie clip on the Stage.

  3. Right-click the movie clip symbol in the Library panel and select Linkage from the context menu.

  4. Select the Export for ActionScript check box, and type libraryLinkageClassName in the Class text input field. Click OK.

  5. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:

    var i:Number;

    for (i = 0; i < 5; i++) {

    this.attachMovie("libraryLinkageClassName", "clip" + i + "_mc", i, {_x:(i * 100)});

    }

  6. Select Control > Test Movie to test the code in Flash Player.

Notice how five movie clips duplicate across the top of the Stage. This ActionScript duplicates the movie clip symbol in the library and repositions the clips on the Stage at x coordinates of 0, 100, 200, 300 and 400 pixels. The loop executes five times, with the variable i assigned a value of 0 through 4. On the last iteration of the loop, the value of i increments to 4 and the second expression (i < 5) is no longer true, which causes the loop to exit.

 

Using for..in loops

TOP

Use the for..in statement to loop through (or iterate through) the children of a movie clip, properties of an object, or elements of an array. Children, referenced previously, include other movie clips, functions, objects, and variables. Common uses of the for..in loop include looping over instances on a timeline or looping over the key/value pairs within an object. Looping over objects can be an effective way to debug applications because it lets you see what data returns from web services or external documents such as text or XML files.

For example, you can use a for...in loop to iterate through the properties of a generic object (object properties are not kept in any particular order, so properties appear in a random order):

var myObj:Object = {x:20, y:30};

for (var i:String in myObj) {

trace(i + ": " + myObj[i]);

}

This code outputs the following in the Output panel:

x: 20

y: 30

You can also iterate through the elements of an array:

var myArray:Array = ["one", "two", "three"];

for (var i:String in myArray) {

trace(myArray[i]);

}

This code outputs the following in the Output panel:

three

two

one

NOTE : You cannot iterate through the properties of an object if it is an instance of a custom class, unless the class is a dynamic class. Even with instances of dynamic classes, you are able to iterate only through properties that are added dynamically.

NOTE :  The curly braces ({}) used to enclose the block of statements to be executed by the for..in statement are not necessary if only one statement executes.

The following example uses for..in to iterate over the properties of an object:

To create a for loop:

  1. Select File > New and then select Flash Document.

  2. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:

    var myObj:Object = {name:"Tara", age:27, city:"San Francisco"};

    var i:String;

    for (i in myObj) {

    trace("myObj." + i + " = " + myObj[i]);

    }

  3. Select Control > Test Movie to test the code in Flash Player.

    When you test the SWF file, you should see the following text in the Output panel:

    myObj.name = Tara

    myObj.age = 27

    myObj.city = San Francisco

If you write a for..in loop in a class file (an external ActionScript file), instance members are not available within the loop, but static members are. However, if you write a for..in loop in a FLA file for an instance of the class, instance members are available but static members are not.

 

Using while loops

TOP

Use the while statement to repeat an action while a condition exists, similar to an if statement that repeats as long as the condition is true.

A while loop evaluates an expression and executes the code in the body of the loop if the expression is true. If the condition evaluates to true, a statement or series of statements runs before looping back to evaluate the condition again. When the condition evaluates to false, the statement or series of statements is skipped and the loop ends. Using while loops can be very useful when you aren't sure of how many times you'll need to loop over a block of code.

For example, the following code traces numbers to the Output panel:

var i:Number = 0;

while (i < 5) {

trace(i);

i++;

}

You see the following numbers traced to the Output panel:

0

1

2

3

4

One disadvantage of using a while loop instead of a for loop is that infinite loops are easier to write with while loops. The for loop example code does not compile if you omit the expression that increments the counter variable, but the while loop example does compile if you omit that step. Without the expression that increments i, the loop becomes an infinite loop.

To create and use a while loop in a FLA file, follow this example.

To create a while loop:

  1. Select File > New and then select Flash Document.

  2. Open the Components panel and drag a DataSet component onto the Stage.

  3. Open the Property inspector (Window > Properties > Properties) and type the instance name users_ds.

  4. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:

    var users_ds:mx.data.components.DataSet;

    //

    users_ds.addItem({name:"Irving", age:34});

    users_ds.addItem({name:"Christopher", age:48});

    users_ds.addItem({name:"Walter", age:23});

    //

    users_ds.first();

    while (users_ds.hasNext()) {

    trace("name:" + users_ds.currentItem["name"] + ", age:" + users_ds.currentItem["age"]);

    users_ds.next();

    }

  5. Select Control > Test Movie to test the document.

    The following information is displayed in the Output panel:

    name:Irving, age:34

    name:Christopher, age:48

    name:Walter, age:23

 

About do..while loops

TOP

You can use the do..while statement to create the same kind of loop as a while loop. However, the expression is evaluated at the bottom of the code block in a do..while loop (it's checked after the code block executes), so the loop always runs at least one time. The statements execute only if the condition evaluates to true.

The following code shows a simple example of a do..while loop that generates output even though the condition is not met.

var i:Number = 5;

do {

trace(i);

i++;

} while (i < 5);

// Output: 5

When you use loops, you need to avoid writing infinite loops. If the condition in a do..while loop continuously evaluates to true, you create an infinite loop that displays a warning or crashes Flash Player. Use a for loop instead if you know how many times you want to loop.

 

Using nested loops in your ActionScript

TOP

The following example demonstrates how to make an array of objects and display each of the values in the nested structure. This example shows you how to use the for loop to loop through each item in the array and how to use the for..in loop to iterate through each key/value pair in the nested objects.

Nesting a loop within another loop:

  1. Create a new Flash document.

  2. Select File > Save As and name the document loops.fla.

  3. Add the following code to Frame 1 of the Timeline:

    var myArr:Array = new Array();

    myArr[0] = {name:"One", value:1};

    myArr[1] = {name:"Two", value:2};

    //

    var i:Number;

    var item:String;

    for (i = 0; i < myArr.length; i++) {

    trace(i);

    for (item in myArr[i]) {

    trace(item + ": " + myArr[i][item]);

    }

    trace("");

    }

  4. Select Control > Test Movie to test your code.

    The following is displayed in the Output panel.

    0

    name: One

    value: 1

    1

    name: Two

    value: 2

You know how many items are in the array, so you can loop over each item using a simple for loop. Because each object in the array can have different name/value pairs, you can use a for..in loop to iterate over each value and display the results in the Output panel.

 

About arrays

TOP

An array is an object whose properties are identified by numbers representing their positions in the structure. Essentially, an array is a list of items. It's important to remember that each element in an array doesn't have to be the same data type. You can mix numbers, dates, strings, and objects and even add a nested array at each array index.

The following example is a simple array of month names.

var myArr:Array = new Array();

myArr[0] = "January";

myArr[1] = "February";

myArr[2] = "March";

myArr[3] = "April";

The previous array of month names can also be rewritten as follows:

var myArr:Array = new Array("January", "February", "March", "April");

Or, you can use shorthand syntax, as follows:

var myArr:Array = ["January", "February", "March", "April"];

An array is like a structure for data. An array is like an office building, where each floor contains a different piece of data (such as accounting on floor 3, and engineering on floor 5). As such, you can store different kinds of data in a single array, including other arrays. Each floor of this building can contain multiple kinds of content (executives and accounting might share floor 3).

An array contains elements, which are equivalent to each floor of the building. Each element has a numeric position (the index), which is how you refer to each element's position in the array. This is similar to how each floor in a building has a floor number. Each element can either hold a piece of data (which could be a number, string, Boolean value, or even an array or object) or be empty.

You can also control and modify the array itself. For example, you might want to move the engineering department to the basement of the building. Arrays let you move values around, and they let you change the size of the array (say, renovate the building and add more floors or remove floors). As such, you can add or remove elements and move values to different elements.

Therefore, the building (the array) contains floors (the elements), which are numbered floors (the index), and each floor contains one or more departments (the values).

You can find a sample source file, array.fla, in the Samples folder on your hard disk. This sample illustrates array manipulation using ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories:

  • In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays.

  • On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.

 

Using arrays

TOP

There are several different ways you can use arrays in your work. You can use them to store lists of objects, such as a bunch of returned items. If you load data from remote web servers, you might even receive data as an array of nested objects. Often, arrays contain data in a similar format. For example, if you build an audio application in Flash, you might have a user's playlist stored as an array of song information, stored in objects. Each object contains the song name, artist name, song duration, location of a sound file (such as an MP3), or any other information that you might need to associate with a particular file.

The location of an item in an array is called the index. All arrays are zero-based, which means that the first element in the array is [0], the second element is [1], and so on.

There are different kinds of arrays, which you'll discover in the following sections. The most common arrays use a numerical index to look up a particular item in an indexed array. The second kind of array is called an associative array and uses a text index instead of a numerical index to look up information.

The built-in Array class lets you access and manipulate arrays. To create an Array object, you use the constructor new Array() or the array access operator ([]). To access the elements of an array, you also use the array access ([]) operator. The next example uses an indexed array.

To use arrays in your code:

  1. Create a new Flash document, and save it as basicArrays.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    // define a new array

    var myArr:Array = new Array();

    // define values at two indexes

    myArr[1] = "value1";

    myArr[0] = "value0";

    // iterate over the items in the array

    var i:String;

    for (i in myArr) {

    // trace the key/value pairs

    trace("key: " + i + ", value: " + myArr[i]);

    }

    In the first line of ActionScript, you define a new array to hold the values. Then, you define data (value0 and value1) at two indexes of the array. You use a for..in loop to iterate over each of the items in that array and display the key/value pairs in the Output panel using a trace statement.

  3. Select Control > Test Movie to test your code.

    The following text is displayed in the Output panel:

    key: 0, value: value0

    key: 1, value: value1

You can find a sample source file, array.fla, in the Samples folder on your hard disk. This sample illustrates array manipulation using ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories:

  • In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays.

  • On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.

 

About modifying arrays

TOP

You can also control and modify the array using ActionScript. You can move values around an array, or you can change the size of the array. For example, if you want to exchange data at two indexes in an array, you can use the following code:

var buildingArr:Array = new Array();

buildingArr[2] = "Accounting";

buildingArr[4] = "Engineering";

trace(buildingArr); // undefined,undefined,Accounting,undefined,Engineering

var temp_item:String = buildingArr[2];

buildingArr[2] = buildingArr[4];

buildingArr[4] = temp_item;

trace(buildingArr); // undefined,undefined,Engineering,undefined,Accounting

You might wonder why you need to create a temporary variable in the previous example. If you copied the contents of array index 4 into array index 2 and vice versa, the original contents of array index 2 would be lost. When you copy the value from one of the array indexes into a temporary variable, you can save the value and safely copy it back later in your code. For example, if you use the following code instead, you can see that the value of array index 2 (Accounting) has been lost. Now you have two engineering teams but no accountants.

// wrong way (no temporary variable)

buildingArr[2] = buildingArr[4];

buildingArr[4] = buildingArr[2];

trace(buildingArr); // undefined,undefined,Engineering,undefined,Engineering

You can find a sample source file, array.fla, in the Samples folder on your hard disk. This sample illustrates array manipulation using ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories:

  • In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays.

  • On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.

 

About referencing and finding length

TOP

When you work with arrays, you often need to know how many items exist in the array. This can be very useful when writing for loops that iterate through every element in the array and execute a series of statements. You can see an example in the following snippet:

var monthArr:Array = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

trace(monthArr); // Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

trace(monthArr.length); // 12

var i:Number;

for (i = 0; i < monthArr.length; i++) {

monthArr[i] = monthArr[i].toUpperCase();

}

trace(monthArr); // JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC

In the previous example, you create an array and populate it with month names. The contents are displayed, and also the array's length. A for loop iterates over each item in the array and converts the value to uppercase, and the array contents are displayed again.

In the following ActionScript, if you create an element at array index 5 in an array, the length of the array returns 6 (because the array is zero based), and not the actual number of items in the array as you might expect:

var myArr:Array = new Array();

myArr[5] = "five";

trace(myArr.length); // 6

trace(myArr); // undefined,undefined,undefined,undefined,undefined,five

You can find a sample source file, array.fla, in the Samples folder on your hard disk. This sample illustrates array manipulation using ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories:

  • In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays.

  • On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.

 

About adding and removing elements

TOP

An array contains elements and each element has a numeric position (the index), which is how you refer to each element's position in the array. Each element can either hold a piece of data or be empty. An element can hold the following data: a .number, string, Boolean, or even an array or object.

When you create elements in an array, you should create the indexes sequentially whenever possible. This helps you when you debug your applications. In About referencing and finding length, you saw that if you assign a single value in an array at index 5, the array length returns as 6. This causes five undefined values to be inserted into the array.

The following example demonstrates how to create a new array, delete an item at a particular index, and add and replace data at an index in an array:

var monthArr:Array = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

delete monthArr[5];

trace(monthArr); // Jan,Feb,Mar,Apr,May,undefined,Jul,Aug,Sep,Oct,Nov,Dec

trace(monthArr.length); // 12

monthArr[5] = "JUN";

trace(monthArr); // Jan,Feb,Mar,Apr,May,JUN,Jul,Aug,Sep,Oct,Nov,Dec

Even though you deleted the item at array index 5, the array length is still 12, and the item at array index 5 changed to a blank string instead of disappearing completely.

You can find a sample source file, array.fla, in the Samples folder on your hard disk. This sample illustrates array manipulation using ActionScript. The code in the sample creates an array and sorts, adds, and removes items of two List components. Find the sample file in the following directories:

In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays.

On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.

 

Creating indexed arrays

TOP

Indexed arrays store a series of one or more values. You can look up items by their position in the array, which you might have done in earlier sections. The first index is always the number 0, and the index increments by one for each subsequent element that you add to the array. You can create an indexed array by calling the Array class constructor or by initializing the array with an array literal. You create arrays using the Array constructor and an array literal in the next example.

To create an indexed array:

  1. Create a new Flash document, and save it as indexArray.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    var myArray:Array = new Array();

    myArray.push("one");

    myArray.push("two");

    myArray.push("three");

    trace(myArray); // one,two,three

    In the first line of ActionScript, you define a new array to hold the values.

  3. Select Control > Test Movie to test your code.

    The following text is displayed in the Output panel:

    one,two,three

  4. Return to the authoring tool, and delete the code in the Actions panel.

  5. Add the following ActionScript to Frame 1 of the Timeline:

    var myArray:Array = ["one", "two", "three"];

    trace(myArray); // one,two,three

    In this code you use the array literal to define a new array for your code. This code is the equivalent of the ActionScript you wrote in step 2. When you test the code, you see the same output appear in the Output panel.

 

Creating multidimensional arrays

TOP

In ActionScript, you can implement arrays as nested arrays that are essentially arrays of arrays. Nested arrays, also known as multidimensional arrays, can be thought of as matrices or grids. Therefore, when you are programming, you might use multidimensional arrays to model these kinds of structures. For example, a chess board is a grid of eight columns and rows; you could model the chess board as an array that contains eight elements, each of which is also an array that contains eight elements.

For example, consider a list of tasks that is stored as an indexed array of strings:

var tasks:Array = ["wash dishes", "take out trash"];

If you want to store a separate list of tasks for each day of the week, you can create a multidimensional array with one element for each day of the week. Each element contains an indexed array that stores the list of tasks.

CAUTION : When you use the array access operator, the ActionScript compiler cannot check whether the accessed element is a valid property of the object.

To create a basic multidimensional array and retrieve elements from the array:

  1. Create a new Flash document, and save it as multiArray1.fla.

    Add the following ActionScript to Frame 1 of the Timeline:

    var twoDArray:Array = new Array(new Array("one","two"), new Array("three", "four"));

    trace(twoDArray);

    This array, twoDArray, consists of two array elements. These elements are themselves arrays consisting of two elements. In this case, twoDArray is the main array that contains two nested arrays.

  2. Select Control > Test Movie to test the code. You see the following display in the Output panel.

    one,two,three,four

  3. Return to the authoring tool and open the Actions panel. Comment out the trace statement, as shown below:

  4. // trace(twoDArray);

  5. Add the following ActionScript at the end of your code on Frame 1 of the Timeline:

    trace(twoDArray[0][0]); // one

    trace(twoDArray[1][1]); // four

    To retrieve elements of a multidimensional array, you use multiple array access ([]) operators after the name of the top-level array. The first [] refers to the index of the top-level array. Subsequent array access operators refer to elements of nested arrays.

  6. Select Control > Test Movie to test the code. You see the following display in the Output panel.

    one

    four

You can use nested for loops to create multidimensional arrays. The next example shows you how.

To create a multidimensional array using a for loop:

  1. Create a new Flash document, and save it as multiArray2.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    var gridSize:Number = 3;

    var mainArr:Array = new Array(gridSize);

    var i:Number;

    var j:Number;

    for (i = 0; i < gridSize; i++) {

    mainArr[i] = new Array(gridSize);

    for (j = 0; j < gridSize; j++) {

    mainArr[i][j] = "[" + i + "][" + j + "]";

    }

    }

    trace(mainArr);

    This ActionScript creates a 3 x 3 array and sets the value of each array node to its index. Then you trace the array (mainArr).

  3. Select Control > Test Movie to test the code.

    You see the following display in the Output panel:

    [0][0],[0][1],[0][2],[1][0],[1][1],[1][2],[2][0],[2][1],[2][2]

You can also use nested for loops to iterate through the elements of a multidimensional array, as shown in the next example.

To use a for loop to iterate a multidimensional array:

  1. Create a new Flash document, and save it as multiArray3.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    // from previous example

    var gridSize:Number = 3;

    var mainArr:Array = new Array(gridSize);

    var i:Number;

    var j:Number;

    for (i = 0; i < gridSize; i++) {

    mainArr[i] = new Array(gridSize);

    for (j = 0; j < gridSize; j++) {

    mainArr[i][j] = "[" + i + "][" + j + "]";

    }

    }

    In this code, seen in the previous example, the outer loop iterates through each element of mainArray. The inner loop iterates through each nested array and outputs each array node.

  3. Add the following ActionScript to Frame 1 of the Timeline, following the code you entered in step 2:

    // iterate through elements

    var outerArrayLength:Number = mainArr.length;

    for (i = 0; i < outerArrayLength; i++) {

    var innerArrayLength:Number = mainArr[i].length;

    for (j = 0; j < innerArrayLength; j++) {

    trace(mainArr[i][j]);

    }

    }

    This ActionScript iterates through the elements of the array. You use the length property of each array as the loop condition.

  4. Select Control > Test Movie to view the elements that are displayed in the Output panel. You will see the following in the Output panel:

    [0][0]

    [0][1]

    [0][2]

    [1][0]

    [1][1]

    [1][2]

    [2][0]

    [2][1]

    [2][2]

 

Creating associative arrays

TOP

An associative array, which is like an object, is made of unordered keys and values. Associative arrays use keys instead of a numeric index to organize stored values. Each key is a unique string, and it is associated with and used to access one value. That value can be a data type such as Number, Array, Object, and so on. When you create code to find a value that's associated with a key, you are indexing or performing a lookup. This is what you will probably use associative arrays for most often.

The association between a key and value is commonly referred to as its binding; the key and value are mapped to each other. For example, a contact book might be considered an associative array, where the names are the keys and email addresses are the values

NOTE : Associative arrays are unordered collections of key and value pairs. Your code should not expect the keys of an associative array to be in a specific order.

When you use associative arrays, you can call the array element you need using a string rather than a number, which is often easier to remember. The downside is that these arrays aren't as useful in a loop because they do not use numbers as the index value. They are useful when you need to look up by key values frequently. For example, if you had an array of names and ages that you needed to refer to a lot, you might use an associative array.

The following example demonstrates how to create an object and define a series of properties in an associative array.

To create a simple associative array:

  1. Create a new Flash document.

  2. Type the following ActionScript on Frame 1 of the Timeline:

    // Define the object to use as an associative array.

    var someObj:Object = new Object();

    // Define a series of properties.

    someObj.myShape = "Rectangle";

    someObj.myW = 480;

    someObj.myH = 360;

    someObj.myX = 100;

    someObj.myY = 200;

    someObj.myAlpha = 72;

    someObj.myColor = 0xDFDFDF;

    // Display a property using dot operator and array access syntax.

    trace(someObj.myAlpha); // 72

    trace(someObj["myAlpha"]); // 72

    The first line of ActionScript defines a new object (someObj) that you use as the associative array. Following this, you define a series of properties in someObj. Finally, you display a property that you select using both dot operator and array access syntax.

    NOTE : You can access variables in an associative array using two different methods: dot syntax (someObj.myColor) and array syntax (someObj['myColor']).

  3. Select Control > Test Movie to test your ActionScript.

The Output panel displays the number 72 twice, which represents both of the alpha levels that you traced.

There are two ways to create associative arrays in ActionScript 2.0:

  • Use an Object constructor

  • Use an Array constructor

Both of these ways are demonstrated in upcoming examples.

NOTE : The previous example used an Object constructor to create an associative array.

If you use the Object constructor to create an associative array, you can take advantage of initializing your array with an object literal. An instance of the Object class, also called a generic object, is functionally identical to an associative array. In fact, Object instances are essentially associative arrays. You might use associative arrays for dictionary-like functionality, when it's more convenient to have string keys rather than numerical indices. Each property name of the generic object serves as the key that provides access to a stored value. For more information on literals, see About literals. For more information on classes, see Classes.

To create an associative array using an Object constructor:

  1. Create a new Flash document, and save it as assocArray.fla.

    Add the following ActionScript to Frame 1 of the Timeline:

    var monitorInfo:Object = {type:"Flat Panel", resolution:"1600 x 1200"};

    trace(monitorInfo["type"] + ", " + monitorInfo["resolution"]);

    This code creates an associative array called monitorInfo, and uses an object literal to initialize the array with two key/value pairs.

    NOTE : If you do not need to initialize the array at declaration time, you can use the Object constructor to create the array:

    var monitorInfo:Object = new Object();

  2. Select Control > Test Movie.

    The Output panel displays the following text:

    Flat Panel, 1600 x 1200

  3. Add the following ActionScript to Frame 1 of the Timeline, following the code you entered previously:

    monitorInfo["aspectRatio"] = "16:10";

    monitorInfo.colors = "16.7 million";

    trace(monitorInfo["aspectRatio"] + ", " + monitorInfo.colors);

    After you use using either an object literal or the Object class constructor to create the array, you can add new values to the array using either the bracket operator ([]) or the dot operator (.), as demonstrated in this code. The code you just typed adds two new values to monitorInfo array.

  4. Select Control > Test Movie.

    The Output panel displays the following text:

    16:10, 16.7 million

    Note that a key can contain a space character. This is possible with the bracket operator, but generates an error if you attempt this with the dot operator. Using spaces in your key names is not recommended. For more information on bracket operators and dot operators, see About operators. For more information on well-formatted code, see Formatting ActionScript syntax.
    The second way to create an associative array is to use the Array constructor and then use either the bracket operator ([]) or the dot operator (.) to add key and value pairs to the array. If you declare your associative array to be of type Array, you cannot use an object literal to initialize the array.

NOTE : There is no advantage to using the Array constructor to create an associative array. The Array constructor is best for creating indexed arrays.

The next example demonstrates how to use the Array constructor to create an associative array.

To create an associative array using the Array constructor:

  1. Create a new Flash document, and save it as assocArray2.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    var monitorInfo:Array = new Array();

    monitorInfo["type"] = "Flat Panel";

    monitorInfo["resolution"] = "1600 x 1200";

    trace(monitorInfo["type"] + ", " + monitorInfo["resolution"]);

    This code creates an associative array named monitorInfo using the Array constructor and adds a key called type and a key called resolution, along with their values.

  3. Select Control > Test Movie.

    The Output panel displays the following text:

    Flat Panel, 1600 x 1200

    NOTE : There is no advantage to using the Array constructor to create an associative array. The Array constructor is best for creating indexed arrays.

Associative arrays are essentially instances of the Object class, and there is no advantage of creating associative arrays using the Array constructor. Even though you create an associative array using the new Array() constructor, you cannot use any of the Array class's methods and properties (such as sort() or length) when using an associative array. If you want to use key/value pairs instead of a numeric index, you should use the Object class instead of an associative array.

 

About operators

TOP

This section describes general rules about common types of operators, operator precedence, and operator associativity.

Operators are characters that specify how to combine, compare, or change values in an expression. An expression is any statement that Flash can evaluate and that returns a value. You can create an expression by combining operators and values or by calling a function. For more information on expressions, see About syntax, statements, and expressions.

For example, a mathematical expression uses numerical operators to manipulate the values you use. Examples of operator characters are +, <, *, and =. An expression consists of operators and operands, and they are any legal combination of ActionScript symbols that represent a value. An operand is the part of your code that the operator performs actions on. For example, in the expression x + 2, x and 2 are operands and + is an operator.

You use expressions and operators frequently throughout your code. You can combine operators and values to create an expression, or you can call a function.

NOTE : This section describes how to use each type of operator; however, there isn't space to cover each one. For information on every operator, including special operators that don't fall into the following categories, see the ActionScript 2.0 Language Reference.

The parts of your code that the operator performs actions on are called operands. For example, you can use the addition (+) operator to add values of a numeric literal. You could do this to add the value of a variable called myNum.

myNum + 3;

In this example, myNum and 3 are operands.

 

Using operators to manipulate values

TOP

Operators are commonly used to manipulate values in Flash. For example, you might want to create a game in Flash where the score changes depending on the user's interaction with instances on the Stage. You can use a variable to hold the value and operators to manipulate the value of the variable.

For example, you might want to increase the value of a variable called myScore. The following example demonstrates how to use the + (addition) and += (addition assignment) operators to add and increment values in your code.

To manipulate values using operators:

  1. Create a new Flash document.

  2. Open the Actions panel (Window > Actions) and type the following code into the Script pane:

    // example one

    var myScore:Number = 0;

    myScore = myScore + 1;

    trace("Example one: " + myScore); // 1

    // example two

    var secondScore:Number = 1;

    secondScore += 3;

    trace("Example two: " + secondScore); // 4

  3. Select Control > Test Movie.

    The Output panel displays the following text:

    Example one: 1

    Example two: 4

    The addition operator is fairly straightforward, because it adds two values together. In the first code example, it adds the current value of myScore and the number 1, and then stores the result into the variable myScore.

The second code example uses the addition assignment operator to add and assign a new value in a single step. You can rewrite the line myScore = myScore + 1 (from the previous exercise) as myScore++ or even myScore += 1. The increment operator (++) is a simplified way of saying myScore = myScore + 1, because it handles an increment and assignment simultaneously.

You can see an example of the increment operator in the following ActionScript:

var myNum:Number = 0;

myNum++;

trace(myNum); // 1

myNum++;

trace(myNum); // 2

Notice that the previous code snippet doesn't have assignment operators. It relies on the increment operator instead.

You can manipulate the value of a variable using operators while a condition is true. For example, you can use the increment operator (++) to increment the variable i while the condition is true. In the following code, the condition is true while i is less than the value of 10. While that is true, you increment i one number higher using i++.

var i:Number;

for (i = 1; i < 10; i++) {

trace(i);

}

The Output panel displays the numbers 1 through 9, which is i incrementing in value until it reaches the end condition (i is equal to 10), when it stops. The last value displayed is 9. Therefore, the value of i is 1 when the SWF file starts playing, and 9 after the trace completes.

 

About operator precedence and associativity

TOP

When you use two or more operators in a statement, some operators take precedence over other operators. Operator precedence and associativity determine the order in which operators are processed. ActionScript has a hierarchy that determines which operators execute before others. There is a table that outlines this hierarchy at the end of this section.

Although it may seem natural to those familiar with arithmetic or basic programming that the compiler processes the multiplication (*) operator before the addition (+) operator, the compiler needs explicit instructions about which operators to process first. Such instructions are collectively referred to as operator precedence.

You can see an example of operator precedence when you work with the multiplication and addition operators:

var mySum:Number;

mySum = 2 + 4 * 3;

trace(mySum); // 14

You see the output of this statement is 14, because multiplication has a higher operator precedence. Therefore, 4 * 3 is evaluated first and the result is added to 2.

You can control what happens by enclosing expressions in parentheses. ActionScript defines a default operator precedence that you can alter using the parentheses (()) operator. When you put parentheses around the addition expression, ActionScript performs the addition first:

var mySum:Number;

mySum = (2 + 4) * 3;

trace(mySum); // 18

Now the output of this statement is 18.

It's also possible for operators to have the same precedence. In this case, the associativity determines the order in which the operators perform. You can either have left-to-right associativity or right-to-left associativity.

Take a look at the multiplication operator again. It has left-to-right associativity, so the following two statements are the same.

var mySum:Number;

var myOtherSum:Number;

mySum = 2 * 4 * 3;

myOtherSum = (2 * 4) * 3;

trace(mySum); // 24

trace(myOtherSum); // 24

You might encounter situations in which two or more operators of the same precedence appear in the same expression. In these cases, the compiler uses the rules of associativity to determine which operator to process first. All of the binary operators, except the assignment operators, are left-associative, which means that operators on the left are processed before operators on the right. The assignment operators and the conditional (?:) operator are right-associative, which means that the operators on the right are processed before operators on the left. For more information on assignment operators, see Using assignment operators. For more information on the conditional (?:) operator, see About the conditional operator.

For example, consider the less than (<) and greater than (>) operators, which have the same precedence. If both operators are used in the same expression, the operator on the left is processed first because both operators are left-associative. This means that the following two statements produce the same output:

trace(3 > 2 < 1); // false

trace((3 > 2) < 1); // false

The greater than (>) operator is processed first, which results in a value of true because the operand 3 is greater than the operand 2. The value true is then passed to the less than (<) operator, along with the operand 1. The less than (<) operator converts the value true to the numeric value 1 and compares that numeric value to the second operand 1 to return the value false (the value 1 is not less than 1).

Consider the order of operands in your ActionScript, particularly when you set up complex conditions and you know how often one of those conditions is true. For example, if you know that i will be greater than 50 in your condition, you need to write i<50 first. Therefore, it's checked first, and the second condition that you write doesn't need to be checked as often.

The following table lists all the ActionScript operators and their associativity, from highest to lowest precedence.

Operator

Description

Associativity

Highest precedence

x++

Post-increment

Left to right

x--

Post-decrement

Left to right

.

Object property access

Left to right

[ ]

Array element

Left to right

( )

Parentheses

Left to right

function ( )

Function call

Left to right

++x

Pre-increment

Right to left

--x

Pre-decrement

Right to left

-

Unary negation, such as x = -1

Left to right

~

Bitwise NOT

Right to left

!

Logical NOT

Right to left

new

Allocate object

Right to left

delete

Deallocate object

Right to left

typeof

Type of object

Right to left

void

Returns undefined value

Right to left

*

Multiply

Left to right

/

Divide

Left to right

%

Modulo

Left to right

+

Unary plus

Right to left

-

Unary minus

Right to left

<<

Bitwise left shift

Left to right

>>

Bitwise right shift

Left to right

>>>

Bitwise right shift (unsigned)

Left to right

instanceof

Instance of (finds the class of which the object is an instance)

Requires Flash Player 6 or later

Left to right

<

Less than

Left to right

<=

Less than or equal to

Left to right

>

Greater than

Left to right

>=

Greater than or equal to

Left to right

==

Equal

Left to right

!=

Not equal

Left to right

&

Bitwise AND

Left to right

^

Bitwise XOR

Left to right

|

Bitwise OR

Left to right

&&

Logical AND

Left to right

||

Logical OR

Left to right

?:

Conditional

Right to left

=

Assignment

Right to left

*=, /=, %=, +=, -=, &=, |=, ^=, <<=, >>=, >>>=

Compound assignment

Right to left

,

Comma

Left to right

Lowest precedence

 

About using operators with strings

TOP

Comparison operators compare strings only if both operands are strings. An exception to this rule is the strict equality (===) operator. If only one operand is a string, ActionScript converts both operands to numbers and performs a numeric comparison on them. For more information on numeric operators, see Using numeric operators.

Except for the equality operator (==), comparison operators (>, >=, <, and <=) affect strings differently than when they operate on other values.

Comparison operators compare strings to determine which is first alphabetically. Strings with uppercase characters precede strings that are lowercase. That means that "Egg" comes before "chicken".

var c:String = "chicken";

var e:String = "Egg";

trace(c < e); // false

var riddleArr:Array = new Array(c, e);

trace(riddleArr); // chicken,Egg

trace(riddleArr.sort()); // Egg,chicken

In this ActionScript, the sort() method of the Array class reorders the contents of the array alphabetically. You can see that the value "Egg" comes before the value "chicken" because uppercase E comes before a lowercase c. If you want to compare the strings regardless of case, you need to convert the strings to uppercase or lowercase before you compare them. For more information on comparison operators, see About equality operators and Using relational and equality operators.

You can use the toLowerCase() or toUpperCase() methods to convert strings to a similar case before you compare them. In the following example, both strings convert to lowercase strings and compare, and now the chicken comes before the egg:

var c:String = "chicken";

var e:String = "Egg";

trace(c.toLowerCase() < e.toLowerCase()); // true

NOTE : Comparison operators compare only two strings. For example, the operators do not compare the values if one operand is a numerical value. If one of the operands is a string, ActionScript converts both operands to numbers and then compares them numerically.

You can use operators to manipulate strings. You can use the addition (+) operator to concatenate string operands. You might have already used the addition operator to concatenate strings when you write trace statements. For example, you might write the following:

var myNum:Number = 10;

trace("The variable is " + myNum + ".");

When you test this code, the Output panel displays the following:

The variable is 10.

In the previous example, the trace statement uses the + operator to concatenate instead of add. When you deal with strings and numbers, Flash sometimes concatenates instead of adding numerically.

For example, you might concatenate two strings from different variables in a single text field. In the following ActionScript code, the variable myNum concatenates with a string, and the string is displayed in the myTxt text field on the Stage.

this.createTextField("myTxt", 11, 0, 0, 100, 20);

myTxt.autoSize = "left";

var myNum:Number = 10;

myTxt.text = "One carrot. " + myNum + " large eggplants.";

myTxt.text += " Lots of vegetable broth.";

This code outputs the following in a text field with the instance name myTxt:

One carrot. 10 large eggplants. Lots of vegetable broth.

The previous example shows how you can use the addition (+) and addition assignment (+=) operators to concatenate strings. Notice how the third line of code uses the addition operator to concatenate the value of the myNum variable into the text field, and the fourth line of code uses the addition assignment operator to concatenate a string onto the existing value of the text field.

If only one of the text string operands is actually a string, Flash converts the other operand into a string. Therefore, the value of myNum converts to a string in the previous example.

NOTE : ActionScript treats spaces at the beginning or end of a string as a literal part of the string.

 

Using dot and array access operators

TOP

You can use the dot operator (.) and the array access operator ([]) to access built-in or custom ActionScript properties. You use dot operators to target certain indexes in an object. For example, if you have an object that contains some user information, you can specify a certain key name in the array access operator to retrieve a user's name, as demonstrated in the following ActionScript:

var someUser:Object = {name:"Hal", id:2001};

trace("User's name is: " + someUser["name"]); // User's name is: Hal

trace("User's id is: " + someUser["id"]); // User's id is: 2001

For example, the following ActionScript uses the dot operator to set certain properties within objects:

myTextField.border = true;

year.month.day = 9;

myTextField.text = "My text";

The dot operator and the array access operator are very similar. The dot operator takes an identifier as its property, but the array access operator evaluates the contents to a name and then accesses the value of that named property. The array access operator lets you dynamically set and retrieve instance names and variables.

The array access operator is useful if you don't know exactly what keys are in an object. When this occurs, you can use a for..in loop to iterate through an object or movie clip and display its contents.

To use dot and array access operators:

  1. In a new Flash document, create a movie clip on the main Timeline.

  2. Select the movie clip and open the Property inspector.

  3. Type in an instance name of myClip.

  4. Add the following ActionScript to Frame 1 of the Timeline:

    myClip.spam = 5;

    trace(myClip.spam); // 5

    If you want to set a value in the myClip instance on the current timeline you can use the dot or array access operators, as demonstrated in this ActionScript. If you write an expression inside the array access operator, it evaluates that expression first and uses the result as the variable name.

  5. Select Control > Test Movie to test the document.

    The Output panel displays 5.

  6. Return to the authoring environment, and replace the first line of ActionScript with the following:

    myClip["spam"] = 10;

  7. Select Control > Test Movie to test the document.

    The Output panel displays 10.

  8. Return to the authoring environment, and double-click the myClip instance.

  9. Add four new instances inside the myClip instance.

  10. Use the Property inspector to add the following instance names to each of the four new instances: nestedClip1, nestedClip2, nestedClip3, nestedClip4.

  11. Add the following code to Frame 1 of the main Timeline:

    var i:Number;

    for (i = 1; i <= 4; i++) {

    myClip["nestedClip" + i]._visible = false;

    }

    This ActionScript toggles the visibility of each of the nested movie clips.

  12. Select Control > Test Movie to test the ActionScript you just added.

    Now the four nested instances are invisible. You're using the array access operator to iterate over each nested movie clip in the myClip instance and set its visible property dynamically. You save time, because you don't have to specifically target each instance.

You can also use the array access operator on the left side of an assignment, which lets you set instance, variable, and object names dynamically:

myNum[i] = 10;

In ActionScript 2.0, you can use the bracket operator to access properties on an object that are created dynamically, in case the class definition for that object is not given the dynamic attribute. You can also create multidimensional arrays using this operator.

 

About postfix operators

TOP

The postfix operators take one operator and either increment or decrement the operator's value. Although these operators are unary operators, they are classified separately from the rest of the unary operators because of their higher precedence and special behavior.

When you use a postfix operator as part of a larger expression, the expression's value is returned before the postfix operator is processed. For example, the following code shows how the value of the expression xNum++ is returned before the value is incremented.

var xNum:Number = 0;

trace(xNum++); // 0

trace(xNum); // 1

When you trace this code, the text in the Output panel reads:

0

1

The operators in this table have equal precedence:

Operator

Operation performed

++

Increment (postfix)

--

Decrement (postfix)

 

About unary operators

TOP

Unary operators take one operand. The increment (++) and decrement (--) operators in this group are prefix operators, which means that they appear before the operand in an expression. They can also appear after the operand, in which case they are postfix operators.

The prefix operators differ from the postfix counterparts because the increment or decrement operation completes before the value of the overall expression is returned. For example, the following code shows how the value of the expression xNum++ is returned after the value is incremented.

var xNum:Number = 0;

trace(++xNum); // 1

trace(xNum); // 1

All of the operators in this table have equal precedence:

Operator

Operation performed

++

Increment (prefix)

--

Decrement (prefix)

+

Unary +

!

Unary - (negation)

typeof

Returns type information

void

Returns undefined value

 

About multiplicative operators

TOP

The multiplicative operators take two operands and perform multiplication, division, or modulo calculations. Other numeric operators include additive operators.

All of the operators in this table have equal precedence:

Operator

Operation performed

*

Multiplication

/

Division

%

Modulo

 

About additive operators

TOP

The additive operators take two operands and perform addition or subtraction calculations. Other numeric operators include multiplicative operators.

The operators in this table have equal precedence:

Operator

Operation performed

+

Addition

-

Subtraction

 

Using numeric operators

TOP

You use numeric operators to add, subtract, divide, and multiply values in ActionScript. You can perform different kinds of arithmetic operations. One of the most common operators is the increment operator, commonly formed as i++. There are more things you can do with this operator.

You can add the increment before (preincrement) or after (postincrement) an operand.

To understand numeric operators in ActionScript:

  1. Create a new Flash document.

  2. Type the following ActionScript into Frame 1 of the Timeline:

    // example one

    var firstScore:Number = 29;

    if (++firstScore >= 30) {

    // should trace

    trace("Success! ++firstScore is >= 30");

    }

    // example two

    var secondScore:Number = 29;

    if (secondScore++ >= 30) {

    // shouldn't trace

    trace("Success! secondScore++ is >= 30");

    }

  3. Select Control > Test Movie to test the ActionScript

    The "Example one" code block traces, but the "Example two" code block does not. The first example uses a preincrement (++firstScore) to increment and calculate firstScore before it's tested against 30. Therefore, firstScore increments to 30 and then tests against 30.

    However, Example two uses a postincrement (secondScore++), which evaluates after the test is performed. Therefore, 29 compares against 30, and then increments to 30 after the evaluation.

When you load data from external sources (such as XML files, FlashVars, web services, and so on), you need to be very careful when you work with numeric operators. Sometimes Flash treats the numbers like strings because the SWF file isn't aware of the number's data type. In this case, you could add 3 and 7 with a result of 37 because both numbers are concatenated like strings instead of adding numerically. In this situation, you need to manually convert the data from strings to numbers using the Number() function.

 

About relational operators

TOP

The relational operators take two operands, compare their values, and return a Boolean value. All of the operators in this table have equal precedence:

Operator

Operation performed

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

instanceof

Checks prototype chain

in

Checks for object properties

 

About equality operators

TOP

The equality operators take two operands, compare their values, and return a Boolean value. All of the operators in this table have equal precedence:

Operator

Operation performed

==

Equality

!=

Inequality

===

Strict equality

!==

Strict inequality

 

Using relational and equality operators

TOP

Relational and equality operators, also called comparison operators, compare values of expressions, and they return either true or false (a Boolean value). You frequently use comparison operators in conditional statements and loops to specify the condition for when the loop should stop.

You can use the equality (==) operator to figure out whether the values or references of two operands are equal, and this comparison returns a Boolean value. String, number, or Boolean operand values compare using a value. Object and array operands are compared by a reference.

In this example, you can see how to use the equality operator to test the array's length and display a message in the Output panel if there are no items in the array.

var myArr:Array = new Array();

if (myArr.length == 0) {

trace("the array is empty.");

}

When you select Control > Test Movie, the string the array is empty appears in the Output panel.

You can use the equality operator to compare values, but you cannot use the equality operator to set values. You might try to use the assignment operator (=) to check for equality.

To use relational and equality operators in your code:

  1. Create a new Flash document.

  2. Type the following ActionScript into Frame 1 of the Timeline:

    var myNum:Number = 2;

    if (myNum == 2) {

    // do something

    trace("It equals 2");

    }

    In this ActionScript, you use the equality operator (==) to check for equality. You check whether the variable myNum equals 2.

  3. Select Control > Test Movie.

    The string It equals 2 appears in the Output panel.

  4. Return to the authoring environment and change:

    var myNum:Number = 2;

    to:

    var myNum:Number = 4;

  5. Select Control > Test Movie again.

    The string It equals 2 doesn't appear in the Output panel.

  6. Return to the authoring environment and change:

    if (myNum == 2) {

    to

    if (myNum = 2) {

  7. Select Control > Test Movie again.

    The string It equals 2 appears in the Output panel again.

    In step 6, you assign the value of 2 to myNum, instead of comparing myNum to 2. In this case, the if statement executes regardless of the previous value of myNum, which can cause unexpected results when you test the Flash document.

The strict equality operator (===) is similar to the equality operator, except it doesn't perform type conversion. If two operands are different types, the equality operator returns false. The strict inequality operator (!==) returns the opposite of the strict equality operator.

The following ActionScript demonstrates the key difference between the equality operator (==) and the strict equality operator (===):

var num1:Number = 32;

var num2:String = new String("32");

trace(num1 == num2); // true

trace(num1 === num2); // false

First, you define numeric variables: num1, and num2. If you compare the variables using the equality operator, Flash tries to convert the values to the same data type and then compare the values to see whether they are equal. When you use the strict equality operator (===) Flash doesn't attempt to do any data type conversion before it compares the values. As a result, Flash sees the variables as two separate values.

In the following example, you'll use the greater than or equal to (>=) operator to compare values and execute code based on the value a user enters into a text field.

To use the greater than or equal to operator in your code:

  1. Select File > New and then select Flash Document to create a new FLA file.

  2. Add the following code to Frame 1 of the main Timeline:

    this.createTextField("myTxt", 20, 0, 0, 100, 20);

    myTxt.type = "input";

    myTxt.border = true;

    myTxt.restrict = "0-9";

    this.createEmptyMovieClip("submit_mc", 30);

    submit_mc.beginFill(0xFF0000);

    submit_mc.moveTo(0, 0);

    submit_mc.lineTo(100, 0);

    submit_mc.lineTo(100, 20);

    submit_mc.lineTo(0, 20);

    submit_mc.lineTo(0, 0);

    submit_mc.endFill();

    submit_mc._x = 110;

    submit_mc.onRelease = function(evt_obj:Object):Void {

    var myNum:Number = Number(myTxt.text);

    if (isNaN(myNum)) {

    trace("Please enter a number");

    return;

    }

    if (myNum >= 10) {

    trace("Your number is greater than or equal to 10");

    } else {

    trace("Your number is less than 10");

    }

    };

  3. Select Control > Test Movie to test the ActionScript.

    You can also check whether certain conditions are true and execute an alternative block if the condition is not true.

  4. Change the condition in your ActionScript to the following.

    if (myNum == 10) {

    trace("Your number is 10");

    } else {

    trace("Your number is not 10");

    }

  5. Select Control > Test Movie to test the ActionScript again.

Except for the strict equality (===) operator, the comparison operators compare strings only if both operands are strings. If only one of the operands is a string, both operands convert to numbers and perform a numeric comparison.

 

About assignment operators

TOP

The assignment operators take two operands and assign a value to one operand based on the value of the other operand. All of the operators in this table have equal precedence:

Operator

Operation performed

=

Assignment

*=

Multiplication assignment

/=

Division assignment

%=

Modulo assignment

+=

Addition assignment

-=

Subtraction assignment

<<=

Bitwise left shift assignment

>>=

Bitwise right shift assignment

>>>=

Bitwise unsigned right shift assignment

&=

Bitwise AND assignment

^=

Bitwise XOR assignment

|=

Bitwise OR assignment


 

Using assignment operators

TOP

You can use the assignment operator (=) to assign a given value to a variable. You might assign a string to a variable, as follows:

var myText:String = "ScratchyCat";

You can also use the assignment operator to assign several variables in the same expression. In the following statement, the value of 10 is assigned the variables numOne, numTwo, and numThree.

var numOne:Number;

var numTwo:Number;

var numThree:Number;

numOne = numTwo = numThree = 10;

You can also use compound assignment operators to combine operations. These operators perform the operation on both operands, and then they assign the new value to the first operand. For example, both of these statements do the same thing:

var myNum:Number = 0;

myNum += 15;

myNum = myNum + 15;

When you work with the assignment operator, you can have problems if you try to add values in an expression, as you can see in the following example:
trace("the sum of 5 + 2 is: " + 5 + 2); // the sum of 5 + 2 is: 52

Flash concatenates the values 5 and 2 instead of adding them. To work around this, you can wrap the expression 5+2 in a pair of parentheses, as shown in the following code:

trace("the sum of 5 + 2 is: " + (5 + 2)); // the sum of 5 + 2 is: 7

 

About logical operators

TOP

You use logical operators to compare Boolean values (true and false) and then return a Boolean value based on the comparison. For example, if you have two operands that evaluate to true, the logical AND (&&) operator returns true. Or if one or both of the operands evaluate to true, the logical OR (||) operator returns true.

The logical operators take two operands and return a Boolean result. The logical operators differ in precedence and are listed in the table in order of decreasing precedence:

Operator

Operation performed

&&

Logical AND

||

Logical OR

 

Using operators in a document

TOP

You often use logical operators with comparison operators to determine the condition of an if statement. This is demonstrated by the next example.

To use logical operators in your code:

  1. Select File > New and create a new Flash document.

  2. Open the Actions panel and type the following ActionScript on Frame 1 of the Timeline:

this.createTextField("myTxt", 20, 0, 0, 100, 20);

myTxt.type = "input";

myTxt.border = true;

myTxt.restrict = "0-9";

this.createEmptyMovieClip("submit_mc", 30);

submit_mc.beginFill(0xFF0000);

submit_mc.moveTo(0, 0);

submit_mc.lineTo(100, 0);

submit_mc.lineTo(100, 20);

submit_mc.lineTo(0, 20);

submit_mc.lineTo(0, 0);

submit_mc.endFill();

submit_mc._x = 110;

submit_mc.onRelease = function():Void {

var myNum:Number = Number(myTxt.text);

if (isNaN(myNum)) {

trace("Please enter a number");

return;

}

if ((myNum > 10) && (myNum < 20)) {

trace("Your number is between 10 and 20");

} else {

trace("Your number is NOT between 10 and 20");

}

};

In this ActionScript, you create a text field at runtime. If you type a number into the text field and click the button on the Stage, Flash uses the logical operator to display a message in the Output panel. The message depends on the value of the number you type into the text field.

When you use operands, you need to be careful of the order. This is particularly the case when you use complex conditions. In the following snippet, you can see how you use the logical AND operator to check that a number is between 10 and 20. Based on the result, you display an appropriate message. If the number is less than 10 or greater than 20, an alternate message is displayed in the Output panel.

submit_mc.onRelease = function():Void {

var myNum:Number = Number(myTxt.text);

if (isNaN(myNum)) {

trace("Please enter a number");

return;

}

if ((myNum > 10) && (myNum < 20)) {

trace("Your number is between 10 and 20");

} else {

trace("Your number is NOT between 10 and 20");

}

};

 

About bitwise shift operators

TOP

The bitwise shift operators take two operands and shift the bits of the first operand to the extent specified by the second operand. All of the operators in this table have equal precedence:

Operator

Operation performed

<<

Bitwise left shift

>>

Bitwise right shift

>>>

Bitwise unsigned right shift

 

About bitwise logical operators

TOP

The bitwise logical operators take two operands and perform bit-level logical operations. The bitwise logical operators differ in precedence and are listed in the table in order of decreasing precedence:

Operator

Operation performed

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

 

About relational operators

TOP

Bitwise operators internally manipulate floating-point numbers to change them into 32-bit integers. The exact operation performed depends on the operator, but all bitwise operations evaluate each binary digit (bit) of the 32-bit integer individually to compute a new value.

Using bitwise operators in Flash isn't very common, but can be useful in some circumstances. For example, you might want to build a permissions matrix for a Flash project, but you don't want to create separate variables for each type of permission. In this case, you might use bitwise operators.

The following example shows how you can use the bitwise OR operator with the Array.sort() method to specify sort options.

To use the bitwise OR operator:

  1. Select File > New and create a new Flash document.

  2. Type the following ActionScript into the Actions panel:

    var myArr:Array = new Array("Bob", "Dan", "doug", "bill", "Hank", "tom");

    trace(myArr); // Bob,Dan,doug,bill,Hank,tom

    myArr.sort(Array.CASEINSENSITIVE | Array.DESCENDING);

    trace(myArr); // tom,Hank,doug,Dan,Bob,bill

    The first line defines an array of random names and traces them to the Output panel. Then you call the Array.sort() method and specify two sort options using the constant values Array.CASEINSENSITIVE and Array.DESCENDING. The result of the sort method causes the items in the array to be sorted in reverse order (z to a). The search is case-insensitive; a and A are treated the same, instead of having a case-sensitive search where Z comes before a.

  3. Select Control > Test Movie to test your ActionScript. The following text is displayed in the Output panel:

    Bob,Dan,doug,bill,Hank,tom

    tom,Hank,doug,Dan,Bob,bill

There are five options available in the sort method:

  • 1 or Array.CASEINSENSITIVE (binary = 1)

  • 2 or Array.DESCENDING (binary = 10)

  • 4 or Array.UNIQUESORT (binary = 100)

  • 8 or Array.RETURNINDEXEDARRAY (binary = 1000)

  • 16 or Array.NUMERIC (binary = 10000)

There are three different ways you can define the sort options for an array:

my_array.sort(Array.CASEINSENSITIVE | Array.DESCENDING); // constants

my_array.sort(1 | 2); // numbers

my_array.sort(3); // adding the numbers

Although it might not be immediately obvious, the number values for the sort options are actually bitwise digits (binary or base 2). The constant value Array.CASEINSENSITIVE equals the numeric value of 1, which also happens to be the binary value of 1. The constant value Array.DECENDING has a numeric value of 2 or a binary value of 10.

Working with binary numbers can get confusing. Binary only has two possible values, 1 or 0, which is why the value 2 is represented as 10. If you want to display the number 3 in binary, it would be 11 (1+10). The number 4 represented in binary is 100, representing 5 in binary is 101, and so on.

The following ActionScript demonstrates how to sort an array of numeric values in descending order by using the bitwise AND operator to add the Array.DESCENDING and Array.NUMERIC constants together.

var scores:Array = new Array(100,40,20,202,1,198);

trace(scores); // 100,40,20,202,1,198

trace(scores.sort()); // 1,100,198,20,202,40

var flags:Number = Array.NUMERIC|Array.DESCENDING;

trace(flags); // 18 (base 10)

trace(flags.toString(2)); // 10010 (binary -- base2)

trace(scores.sort(flags)); // 202,198,100,40,20,1

 

About the conditional operator

TOP

The conditional operator is a ternary operator, which means that it take three operands. The conditional operator is a short-hand method of applying the if..else conditional statement:

Operator

Operation performed

?:

Conditional

 

Using operators in a document

TOP

In the following example, you use the Math.round() method to round calculations to an arbitrary number of decimal places. This method rounds the value of the x parameter up or down to the nearest integer, and then returns the value. After you slightly modify the ActionScript, you can make Flash round numbers to a certain number of decimal places instead.

In the next example, you also use the division and multiplication operators to calculate a user's score based on the number of correct answers divided by the total number of questions that are asked. The user's score can multiply by a number and display to get a score between 0% and 100%. Then you use the addition operator to concatenate the user's score into a string that is displayed in the Output panel.

To use operators in ActionScript:

  1. Create a new Flash document.

  2. Type the following ActionScript on Frame 1 of the main Timeline:

    var correctAnswers:Number = 11;

    var totalQuestions:Number = 13;

    //round to the nearest integer

    //var score:Number = Math.round(correctAnswers / totalQuestions * 100);

    //round to two decimal places

    var score:Number = Math.round(correctAnswers / totalQuestions * 100 * 100) / 100;

    trace("You got " + correctAnswers + " out of " + totalQuestions + " answers correct, for a score of " + score + "%.");

  3. Select Control > Test Movie.

    The Output panel displays the following text:

    You got 11 out of 13 answers correct, for a score of 84.62%.

    When you call Math.round() in this example, the score rounds to the nearest integer (85) and is displayed in the Output panel. If you multiply the number by an additional 100, before you call Math.round(), and then divide by 100, you can make Flash round the number to 2 decimal places. This results in a more accurate score.

  4. Try changing the correctAnswers variable to 3 and select Control > Test Movie to test the SWF file again.

If you are building a testing application, you might want to create a series of true/false or multiple choice questions using the RadioButton and Label components. After users finish answering each of the questions and click the submit button, you can compare their answers to an answer key and then calculate their score.

 

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash