marq

Dr. Charles Simonyi is the Father of Modern Microsoft Excel                                           JavaScript was originally developed by Brendan Eich of Netscape under the name Mocha, later LiveScript, and finally renamed to JavaScript.                                           The word "Biology" is firstly used by Lamarck and Treviranus                                           Hippocrates (460-370 bc) is known as father of medicine.                                           Galene, 130-200 is known as father of Experimental Physology                                           Aristotle (384-322 BC) is known as Father of Zoology because he wrote the construction and behavior of different animals in his book "Historia animalium"                                           Theophrastus(370-285 BC) is known as father of Botany because he wrote about 500 different plants in his book "Historia Plantarum".                                           John Resig is known as Father of Jquery -                                          HTML is a markup language which is use to design web pages. It was invented in 1990 by Tim Berners-Lee.                                                                The Google was founded by Larry Page and Sergey Brin.                                                                Rasmus Lerdorf was the original creator of PHP. It was first released in 1995.                                                               Facebook was founded by Mark Zuckerberg                                                               Bjarne Stroustrup, creator of C++.                                                                Dennis Ritchie creator of C                                                                                                                              James Gosling, also known as the "Father of Java"                                          At 11.44%, Bihar is India's fastest growing state                                          Father of HTML -Tim Berners Lee                                          orkut was created by Orkut Büyükkökten, a Turkish software engineer                    Photoshop: It came about after Thomas Knoll, a PhD student at the University of Michigan created a program to display grayscale images on a monochrome monitor which at the time was called 'Display'.

Flash ActionScripting



The object-oriented programming (OOP) features in ActionScript 2.0 are based on the ECMAScript 4 Draft Proposal currently in development by ECMA TC39-TG1 (see www.mozilla.org/js/language/es4/index.html). Because the ECMA-4 proposal is not yet a standard, and because it is still changing, ActionScript 2.0 is loosely based on this specification. ActionScript 2.0 supports all the standard elements of the ActionScript language; it lets you write scripts that more closely adhere to standards used in other object-oriented languages, such as Java. ActionScript 2.0 should be of interest primarily to intermediate or advanced Flash developers who are building applications that require the implementation of classes and subclasses. ActionScript 2.0 also lets you declare the object type of a variable when you create it (see “About assigning data types and strict data typing” on page 45) and provides significantly improved compiler errors (see Appendix A, “Error Messages,” on page 707). Key facts about ActionScript 2.0 include the following points:
■ Scripts that use ActionScript 2.0 to define classes or interfaces must be stored as external script files, with a single class defined in each script; that is, classes and interfaces cannot be defined in the Actions panel. ■ You can import individual class files implicitly (by storing them in a location specified by global or document-specific search paths and then using them in a script) or explicitly (by using the import command); you can import packages (collections of class files in a directory) by using wildcards. ■ Applications developed with ActionScript 2.0 are supported by Flash Player 6 and later. C A U T I O N The default publish setting for new files created in Flash CS3 is ActionScript 3.0. If you plan to modify an existing FLA file with ActionScript 1.0 or ActionScript 2.0 to use ActionScript 2.0 syntax, ensure that the FLA file specifies ActionScript 2.0 in its publish settings. If it does not, your file will compile incorrectly, although Flash will not
necessarily generate compiler errors.32 About ActionScrip


What is ActionScript
The main features of ActionScript 2.0 include the following:
Familiar object-oriented programming (OOP) model The primary feature of ActionScript 2.0 is a familiar model for creating object-oriented programs. ActionScript 2.0 implements several object-oriented concepts and keywords such as class, interface, and packages that will be familiar to you if you’ve programmed with Java. The OOP model provided by ActionScript 2.0 is a “syntactic formalization” of the prototype chaining method used in previous versions of Flash to create objects and establish inheritance. With ActionScript 2.0, you can create custom classes and extend Flash’s built-in classes. Strict data typing ActionScript 2.0 also lets you explicitly specify data types for variables, function parameters, and function return types. For example, the following code declares a variable named userName of type String (a built-in ActionScript data type, or class). var userName:String = ""; Compiler warnings and errors The previous two features (OOP model and strict data typing) enable the authoring tool and compiler to provide compiler warnings and error messages that help you find bugs in your applications faster than was previously possible in Flash. When you use ActionScript 2.0, make sure that the publish settings for the FLA file specify ActionScript 2.0 (the default for Flash CS3 is ActionScript 3.0). Additionally, if you open an older FLA file that uses ActionScript 1.0 and begin rewriting it in ActionScript 2.0, change the publish settings of the FLA file to ActionScript 2.0. If you don’t, your FLA file will not compile correctly, and errors won’t be generated.



About data
Data refers to the numbers, strings, and other information that you can manipulate within Flash. Using data is usually essential when you create applications or websites. You also use data when you create advanced graphics and script-generated animation, and you might have to manipulate values that you use to drive your effects. You can d efine dat a in variables within Flash, or you can load data from external files or sites using XML, web services, built-in ActionScript classes, and so on. You can store data in a database, and then represent that information in several ways in a SWF file. This can include displaying the information in text fields or components, or displaying images in movie clip instances.36 Data and Data Types Some of the most common kinds of data include strings (a sequence of characters, such as names and passages of text), numbers, objects (such as movie clips), Boolean values (true and false), and so on. In this chapter, you’ll also learn about the data types in Flash and how to use them.


About data types
A data type describes a piece of data and the kinds of operations that you can perform on it. You store data in a variable. You use data types when creating variables, object instances, and function definitions to assign the type of data you’re working with. You use many different data types when you write ActionScript. ActionScript 2.0 defines several commonly used data types. Data types describe the kind of value that a variable or ActionScript element can contain. A variable that is assigned a data type can only hold a value within that data type’s set of values. For information on variables,
see “About variables” on page 50.

ActionScript has numerous basic data types that you will probably use frequently in your applications. See the table in “About primitive and complex data types” on page 37 for more information. ActionScript also has core classes, such as Array and Date, that are considered complex or reference data types. For more info on complex and reference data types, see “About primitive and complex data types” on page 37. In addition, all data types and classes are fully defined in ActionScript 2.0 Language Reference. You can also create custom classes for your applications. Any class that you define using the class declaration is also considered a data type. For more information on core and other builtin classes, see “About top-level and built-in classes” on page 246. For more information on creating custom classes, see Chapter 6, “Classes,” on page 187. In ActionScript 2.0, you can assign data types to variables when you declare them. The data types you assign can be any of the core types or can represent a custom class that you created.

For more information, see “About assigning data types and strict data typing” on page 45. When you debug scripts, you might need to determine the data type of an expression or variable to understand why it is behaving a certain way. You can do this with the instanceof and typeof operators (see “About determining data type” on page 49). About data types 37 You can convert one data type to another at runtime using one of the following conversion functions: Array(), Boolean(), Number(), Object(), String(). For a sample of the datatypes.fla file, which shows you how to use data types in an application, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and navigate to the ActionScript2.0/DataTypes folder to access the sample.


About primitive and complex data types
You can divide all the different data type values into two main categories: primitive or complex. A primitive value (or primitive data type) is a value that ActionScript stores at the lowest level of abstraction, which means that operations on the primitive data types are generally faster and more efficient than operations carried out on complex data types. The following data types all define a set of one or more primitive values: Boolean, null, Number, String, and undefined. A complex value (or complex data type) is a value that is not a primitive value and that references the primitive values. Often, these are called reference data types. Complex values belong to the Object data type or a data type that is based on the Object data type. Data types that define sets of complex values include Array, Date, Error, Function, and XML. For more information on these complex data types, see their entries in the ActionScript 2.0 Language Reference. Variables that contain primitive data types behave differently in certain situations than those containing complex types. For more information, see “Using variables in a project” on page 69.

ActionScript has the following basic data types that you can use in your applications:
Data type Description Boolean Primitive. The Boolean data type consists of two values: true and false.No other values are valid for variables of this type. The default value of Boolean variable that has been declared but not initialized is false.

 MovieClip Complex. 
The MovieClip data type lets you control movie clip symbols using the methods of the MovieClip class. For more information, see “MovieClip data type” on page 40.38 Data and Data Types For a sample of the datatypes.fla file,
 see the Flash Samples page at www.adobe.com/go/ learn_fl_samples. Download and decompress the Samples zip file and navigate to the ActionScript2.0/DataTypes folder to access the sample.


Boolean data type
A Boolean value is one that is either true or false. ActionScript also converts the values true and false to 1 and 0 when appropriate. Boolean values are most often used with logical operators in ActionScript statements that make comparisons to control the flow of a script. null Primitive. The null data type contains the value null. This value means no value—that is, a lack of data. You can assign the null value in a variety of situations to indicate that a property or variable does not have a value assigned to it. The null data type is the default data type for all classes that define complex data types.

An exception to this rule is the Object class, which defaults to undefined. For more information, see “null data type” on page 41. Number Primitive. This data type can represent integers, unsigned integers, and floating point numbers. To store a floating point number, you should include a decimal point in the number. Without the decimal point, the number is stored as an integer. The Number data type can store values from Number.MAX_VALUE (very high) to Number.MIN_VALUE (very low). For more information, see ActionScript 2.0 Language Reference and “Number data type” on page 42.

Object Complex.
 The Object data type is defined by the Object class. The Object class serves as the base class for all class definitions in ActionScript, and it lets you arrange objects inside each other (nested objects). For more information, see “Object data type” on page 42.

String Primitive.
The String data type represents a sequence of 16-bit characters that might include letters, numbers, and punctuation marks. Strings are stored as Unicode characters, using the UTF-16 format. An
operation on a String value returns a new instance of the string. For more information, see “String data type” on page 43.

Undefined Primitive.
The undefined data type contains one value: undefined. This is the default value for instances of the Object class. You can only assign a value of undefined to variables that belong to the Object class. For more
information, see “undefined data type” on page 44.


Void Complex.
The Void data type contains only one value: void. You use this data type to designate functions that don’t return a value. Void is a complex data type that references the primitive Void data type. For more information, see “Void data type” on page 44.

Data type DescriptionAbout data types 39
The following example loads a text file into a SWF file, and displays a message in the Output panel if the text file does not load correctly, or the parameters if it does load successfully. See the comments in the code example for more details.

var my_lv:LoadVars = new LoadVars();
//success is a Boolean value
my_lv.onLoad = function(success:Boolean) {
//if success is true, trace monthNames
if (success) {
trace(my_lv.monthNames);
//if success is false, trace a message
} else {
trace("unable to load text file");
{
;{
my_lv.load("http://www.helpexamples.com/flash/params.txt");

The following example checks that users enter values into two TextInput component instances. Two Boolean variables are created, userNameEntered and isPasswordCorrect, and if both variables evaluate to true, a welcome message is assigned to the titleMessage String variable.

// Add two TextInput components, a Label, and a Button component on the
Stage.
// Strict data type the three component instances
var userName_ti:mx.controls.TextInput;
var password_ti:mx.controls.TextInput;
var submit_button:mx.controls.Button;
var welcome_lbl:mx.controls.Label;
//Hide the label
welcome_lbl.visible = false;
// Create a listener object, which is used with the Button component.
// When the Button is clicked, checks for a user name and password.
var btnListener:Object = new Object();
btnListener.click = function(evt:Object) {
// Checks that the user enters at least one character in the TextInput
// instances and returns a Boolean true/false.

var userNameEntered:Boolean = (userName_ti.text.length > 0);
var isPasswordCorrect:Boolean = (password_ti.text == "vertigo");
if (userNameEntered && isPasswordCorrect) {
var titleMessage:String = "Welcome " + userName_ti.text + "!";
welcome_lbl.text = titleMessage;
//display the label
welcome_lbl.visible = true;
{
;{
submit_button.addEventListener("click", btnListener);40 Data and Data Types
For more information, see “Using functions in Flash” on page 176 and “About logical
operators” on page 155.

MovieClip data type
Movie clips are symbols that can play animation in a Flash application. They are the only data
type that refers to a graphic element. The MovieClip data type lets you control movie clip
symbols using the methods of the MovieClip class.

You do not use a constructor to call the methods of the MovieClip class. You can create a
movie clip instance on the Stage or create an instance dynamically. Then you simply call the
methods of the MovieClip class using the dot (.) operator.

Working with movie clips on the Stage The following example calls the startDrag() and
getURL() methods for different movie clip instances that are on the Stage:
my_mc.startDrag(true);
parent_mc.getURL("http://www.adobe.com/support/" + product);
The second example returns the width of a movie clip called my_mc on the Stage. The targeted
instance must be a movie clip, and the returned value must be a numeric value.
function getMCWidth(target_mc:MovieClip):Number {
return target_mc._width;
{
trace(getMCWidth(my_mc));

Creating movie clips dynamically Using ActionScript to create movie clips dynamically is
useful when you want to avoid manually creating movie clips on the Stage or attaching them
from the library. For example, you might create an image gallery with a large number of
thumbnail images that you want to organize on the Stage. Using
MovieClip.createEmptyMovieClip() lets you create an application entirely using
ActionScript.

To dynamically create a movie clip, use MovieClip.createEmptyMovieClip(), as shown in
the following example:
// Creates a movie clip to hold the container.
this.createEmptyMovieClip("image_mc", 9);
// Loads an image into image_mc.
image_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");About data types 41
The second example creates a movie clip called square_mc that uses the Drawing API to draw
a rectangle. Event handlers and the startDrag() and stopDrag() methods of the MovieClip
class are added to make the rectangle draggable.
this.createEmptyMovieClip("square_mc", 1);
square_mc.lineStyle(1, 0x000000, 100);
square_mc.beginFill(0xFF0000, 100);
square_mc.moveTo(100, 100);
square_mc.lineTo(200, 100);
square_mc.lineTo(200, 200);
square_mc.lineTo(100, 200);
square_mc.lineTo(100, 100);
square_mc.endFill();
square_mc.onPress = function() {
this.startDrag();
;{
square_mc.onRelease = function() {
this.stopDrag();
;{
For more information, see Chapter 10, “Working with Movie Clips,” on page 313 and the

MovieClip entry in the ActionScript 2.0 Language Reference.

null data type
The null data type has only one value, null. This value means no value—that is, a lack of data.
You can assign the null value in a variety of situations to indicate that a property or variable
does not yet have a value assigned to it. For example, you can assign the null value in the
following situations:
■ To indicate that a variable exists but has not yet received a value
■ To indicate that a variable exists but no longer contains a value
■ As the return value of a function, to indicate that no value was available to be returned by
the function
■ As a parameter to a function, to indicate that a parameter is being omitted
Several methods and functions return null if no value has been set. The following example
demonstrates how you can use null to test if form fields currently have form focus:
if (Selection.getFocus() == null) {
trace("no selection");
{42 Data and Data Types

Number data type
The Number data type is a double-precision floating-point number. The minimum value of a number object is approximately 5e-324. The maximum is approximately 1.79E+308. You can manipulate numbers using the arithmetic operators addition (+), subtraction (-), multiplication (*), division (/), modulo (%), increment (++), and decrement (--).

 For more information, see “Using numeric operators” on page 149.

You can also use methods of the built-in Math and Number classes to manipulate numbers. For more information on the methods and properties of these classes, see the Math and Number entries in ActionScript 2.0 Language Reference.

The following example uses the sqrt() (square root) method of the Math class to return the square root of the number 100:
Math.sqrt(100);
The following example traces a random integer between 10 and 17 (inclusive):

var bottles:Number = 0;
bottles = 10 + Math.floor(Math.random() * 7);
trace("There are " + bottles + " bottles");

The following example finds the percent of the intro_mc movie clip that is loaded and represents it as an integer:

var percentLoaded:Number = Math.round((intro_mc.getBytesLoaded() /
intro_mc.getBytesTotal()) * 100);

Object data type
An object is a collection of properties. A property is an attribute that describes the object. For
example, the transparency of an object (such as a movie clip) is an attribute that describes its
appearance. Therefore, _alpha (transparency) is a property. Each property has a name and a
value. The value of a property can be any Flash data type—even the Object data type.
This lets you arrange objects inside each other, or nest them.
To specify objects and their properties, you use the dot (.) operator. For example, in the
following code, hoursWorked is a property of weeklyStats, which is a property of
employee:
employee.weeklyStats.hoursWorked
The ActionScript MovieClip object has methods that let you control movie clip symbol
instances on the Stage. This example uses the play() and nextFrame() methods:
mcInstanceName.play();
mc2InstanceName.nextFrame();About data types 43
You can also create custom objects to organize information in your Flash application. To add
interactivity to an application with ActionScript, you need many pieces of information: for
example, you might need a user’s name, age, and phone number; the speed of a ball; the
names of items in a shopping cart; the number of frames loaded; or the key that the user
pressed last. Creating custom objects lets you organize this information into groups, simplify
your scripting, and reuse your scripts.

The following ActionScript code shows an example of using custom objects to organize
information. It creates a new object called user and creates three properties, name, age, and
phone, which are String and Numeric data types.
var user:Object = new Object();
user.name = "Irving";
user.age = 32;
user.phone = "555-1234";
For more information, see “Example: Writing custom classes” on page 223.

String data type
A string is a sequence of characters such as letters, numbers, and punctuation marks. You enter strings in an ActionScript statement by enclosing them in single (') or double (") quotation marks. A common way that you use the string type is to assign a string to a variable. For example, in
the following statement, "L7" is a string assigned to the variable favoriteBand_str:
var favoriteBand_str:String = "L7";
You can use the addition (+) operator to concatenate, or join, two strings. ActionScript treats spaces at the beginning or end of a string as a literal part of the string. The following expression includes a space after the comma:

var greeting_str:String = "Welcome, " + firstName;
To include a quotation mark in a string, precede it with a backslash character (\). This is called
escaping a character. There are other characters that cannot be represented in ActionScript
except by special escape sequences. The following table lists all the ActionScript escape
characters:

Escape sequence Character
\b Backspace character (ASCII 8)
\f Form-feed character (ASCII 12)
\n Line-feed character (ASCII 10)
\r Carriage return character (ASCII 13)44 Data and Data Types
Strings in ActionScript are immutable, just as they are in Java. Any operation that modifies a
string returns a new string.
The String class is a built-in ActionScript class. For information on the methods and properties of the String class, see the String entry in the ActionScript 2.0 Language Reference.

undefined data type
The undefined data type has one value, undefined, and is automatically assigned to a variable
to which a value hasn’t been assigned, either by your code or user interaction.
The value undefined is automatically assigned; unlike null, you don’t assign undefined to a
variable or property. You use the undefined data type to check if a variable is set or defined.
This data type lets you write code that executes only when the application is running, as

shown in the following example:
if (init == undefined) {
trace("initializing app");
init = true;
{
If your application has multiple frames, the code does not execute a second time because the
init variable is no longer undefined.

Void data type
The Void data type has one value, void, and is used in a function definition to indicate that
the function does not return a value, as shown in the following example:

//Creates a function with a return type Void

function displayFromURL(url:String):Void {}
\t Tab character (ASCII 9)
\" Double quotation mark
\' Single quotation mark
\\ Backslash
\000 - \377 A byte specified in octal
\x00 - \xFF A byte specified in hexadecimal
\u0000 - \uFFFF A 16-bit Unicode character specified in hexadecimal
Escape sequence CharacterAbout data types 45
About assigning data types and strict data typing
You use variables in Flash to hold values in your code. You can explicitly declare the object
type of a variable when you create the variable, which is called strict data typing.
If you do not explicitly define an item as holding either a number, a string, or another data
type, at runtime Flash Player will try to determine the data type of an item when it is assigned.
If you assign a value to a variable, as shown in the following example, Flash Player evaluates at
runtime the element on the right side of the operator and determines that it is of the Number
data type:
var x = 3;
Because x was not declared using strict data typing, the compiler cannot determine the type;
to the compiler, the variable x can have a value of any type. (See “Assigning a data type”
on page 46.) A later assignment might change the type of x; for example, the statement
x = "hello" changes the type of x to String.
ActionScript always converts primitive data types (such as Boolean, Number, String, null, or
undefined) automatically when an expression requires the conversion and the variables aren’t
strictly typed.
Strict data typing offers several benefits at compile time. Declaring data types (strict data
typing) can help prevent or diagnose errors in your code at compile time. To declare a variable
using strict data typing, use the following format:
var variableName:datatype;
Because data type mismatches trigger compiler errors, strict data typing helps you find bugs in
your code at compile time and prevents you from assigning the wrong type of data to an
existing variable. During authoring, strict data typing activates code hinting in the
ActionScript editor (but you should still use instance name suffixes for visual elements).
Using strict data typing helps ensure that you don’t inadvertently assign an incorrect type of
value to a variable. Flash checks for typing mismatch errors at compile time, and displays an
error message if you use the wrong type of value. Therefore, using strict typing also helps to
ensure that you do not attempt to access properties or methods that are not part of an object’s
type. Strict data typing means the ActionScript editor automatically shows code hints
for objects.
N O T E
Strict data typing is sometimes called strong typing a variable.46 Data and Data Types
For more information on creating variables, see “About variables” on page 50. For
information on naming variables, see “About naming variables” on page 55. For more
information on assigning data types, and the types you can assign, see “Assigning a data type”
on page 46.
For a sample of the datatypes.fla file, which shows you how to use data types in an
application, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download
and decompress the Samples zip file and navigate to the ActionScript2.0/DataTypes folder to
access the sample.

Assigning a data type
You need to assign data types whenever you define a variable, whether you declare a variable
using the var keyword, create a function argument, set function return type, or define a
variable to use within a for or for..in loop. To assign a data type, you use post-colon syntax,
which means you follow the variable name with a colon and then the data type:
var my_mc:MovieClip;
There are many possibilities for data types, ranging from the native data types such as
Number, String, Boolean, or built-in classes that are included in Flash Player 8, such as
BitmapData, FileReference, or even custom classes that you or other developers have written.
The most common types of data types you might need to specify are the built-in data types
such as Number, String, Boolean, Array, or Object, which are shown in the following
code examples.

To assign a specific data type to an item, specify its type using the var keyword and postcolon syntax, as shown in the following example:
// Strict typing of variable or object
var myNum:Number = 7;
var birthday:Date = new Date();
// Strict typing of parameters
function welcome(firstName:String, age:Number) {
{
// Strict typing of parameter and return value
function square(myNum:Number):Number {
var squared:Number = myNum * myNum;
return squared;
{About data types 47
You can declare the data type of objects based on built-in classes (Button, Date, and so on) as
well as classes and interfaces that you create. In the following example, if you have a file
named Student.as in which you define the Student class, you can specify that objects you
create are of type Student:
var myStudent:Student = new Student();

For this example, suppose you type the following code:
// in the Student.as class file
class Student {
public var status:Boolean; // property of Student objects
{
// in the FLA file
var studentMaryLago:Student = new Student();
studentMaryLago.status = "enrolled"; /* Type mismatch in assignment
statement: found String where Boolean is required. */
When Flash compiles this script, a type mismatch error is generated because the SWF file

expects a Boolean value.
If you write a function that doesn’t have a return type, you can specify a return type of Void
for that function. Or if you create a shortcut to a function, you can assign a data type of
Function to the new variable. To specify that objects are of type Function or Void, see the

following example:
function sayHello(name_str:String):Void {
trace("Hello, " + name_str);
{
sayHello("world"); // Hello, world
var greeting:Function = sayHello;
greeting("Augustus"); // Hello, Augustus
Another advantage of strict data typing is that Flash automatically shows code hints for builtin objects when they are strictly typed. For more information, see “About assigning data types
and strict data typing” on page 45.
Files published using ActionScript 1.0 do not respect strict data typing assignments at compile
time, so assigning the wrong type of value to a variable that you have strictly typed doesn’t
generate a compiler error.
var myNum:String = "abc";
myNum = 12;
/* No error in ActionScript 1.0, but type mismatch error in ActionScript 2.0

/*48 Data and Data Types

The reason for this is that when you publish a file for ActionScript 1.0, Flash interprets a
statement such as var myNum:String = "abc" as slash syntax rather than as strict typing.
(ActionScript 2.0 doesn’t support slash syntax.) This behavior can result in an object that is
assigned to a variable of the wrong type, causing the compiler to let illegal method calls and
undefined property references pass through unreported.
Files published using ActionScript 2.0 can optionally use data typing. Therefore, if you
implement strict data typing in your code, make sure you set your publish settings to
ActionScript 2.0. You can specify the publish settings and define which version of
ActionScript you want to publish your files as by modifying the publish settings from the
main menu (File > Publish Settings) or by clicking the Settings button in the Property
inspector (make sure no instances are selected). To use a specific version of ActionScript or the
Flash Player, select the Flash tab in the Publish Settings dialog box, and make a selection from
the ActionScript version pop-up menu.
For information on type checking, see “About type checking” on page 48.
About type checking
Type checking refers to verifying that the type of a variable and an expression are compatible.
Therefore, Flash checks that the type you specify for a variable matches the value(s) that you
assign to it. For more information on strict data types and assigning data types, see “About
assigning data types and strict data typing” on page 45 and “Assigning a data type”
on page 46.
Type checking can occur at either compile time or runtime. If you use strict data typing, type
checking occurs at compile time. Because ActionScript is a dynamically typed language,
ActionScript can also type checking at runtime.
For example, the following code does not specify the data type of the parameter xParam. At
runtime, you use the parameter to hold a value of type Number and then a value of type
String. The dynamicTest() function then uses the typeof operator to test whether the
parameter is of type String or Number.
function dynamicTest(xParam) {
if (typeof(xParam) == "string") {
var myStr:String = xParam;
trace("String: " + myStr);
} else if (typeof(xParam) == "number") {
var myNum:Number = xParam;
trace("Number: " + myNum);
{
{
dynamicTest(100);
dynamicTest("one hundred");About data types 49
You do not need to explicitly add data type information in your ActionScript. The
ActionScript compiler lets you use properties and invoke methods that do not exist at compile
time. This lets you create properties or assign dynamically methods at runtime.
An example of the flexibility afforded by dynamic type checking involves the use of properties
and methods that are not known at compile time. Because the code is less restrictive, it can
lead to benefits in some coding situations. For example, the following code creates a function
named runtimeTest() that invokes a method and returns a property, neither of which is
known to the compiler. The code will not generate a compile-time error, but if the property or
method is not accessible at runtime, then a runtime error will occur.
function runtimeTest(myParam) {
myParam.someMethod();
return myParam.someProperty;
{

About determining data type
While testing and debugging your programs, you might discover problems that seem to be
related to the data types of different items. Or if you use variables that are not explicitly
associated with a data type, you might find it useful to know the data type of a given variable.
Using ActionScript, you can determine an item’s data type. You can use the typeof operator
to return information about data.
Use the typeof operator to get the data types, but remember that typeof does not return
information about the class to which an instance belongs.
The following example shows how you can use the typeof operator to return the kind of

object that you trace:
// Create a new instance of LoadVars class.
var my_lv:LoadVars = new LoadVars();
/* typeof operator doesn't specify class, only specifies that my_lv is an
object */
var typeResult:String = typeof(my_lv);
trace(typeResult); // object
In this example, you create a new String variable named myName, and then convert it into a

Number data type:
var myName:String = new String("17");
trace(myName instanceof String); // true
var myNumber:Number = new Number(myName);
trace(myNumber instanceof Number); // true50 Data and Data Types
For more information about these operators, see typeof operator and instanceof
operator in the ActionScript 2.0 Language Reference. For more information on testing and
debugging, see Using Flash. For more information on inheritance and interfaces, see Chapter
7, “Inheritance,” on page 263. For more information on classes, see Chapter 6, “Classes,” on
page 187.




About constants and keywords
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.
For more information on constants and keywords, see the following topics:

■ “Using constants” on page 100
■ “About keywords” on page 102
■ “About reserved words” on page 103

T I P
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.100 Syntax and Language Fundamentals For more information on objects and properties, see “Object data type” on page 42. For a list of constants in the language (such as false and NaN), see the ActionScript Language Elements > Constants category in the ActionScript 2.0 Language Reference.

Using constants
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.adobe.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 more information
on literals, see “About literals” on page 94.About constants and keywords 101
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.102 Syntax and Language Fundamentals
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.
13. Type the following code into the Actions panel.
trace(myExample.EXAMPLE_PRIVATE); // error
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.
For more information on built-in classes and creating custom classes, see Chapter 6,
“Classes,” on page 187.
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 Chapter 3, “Data and
Data Types,” on page 35. ActionScript reserves words in the language for specific use.
Therefore, you can’t use keywords as identifiers (such as variable, function, or label names).
You can find a list of these keywords in “About reserved words” on page 103.About statements 103

About reserved words
Reserved words are words that you cannot use as identifiers in your code because the words are
reserved for use by ActionScript. Reserved words include keywords, which are ActionScript
statements, and words that are reserved for future use. That means you should not use them
for naming your variables, instances, custom classes, and so on; doing so can lead to technical
problems in your work.

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, which are called language constructs.
Therefore, do not use the names of properties, methods, classes, interfaces, component class
names, and interface names as identifiers in your code (such as when you name variables,
classes, or instances).


For more information about reserved keywords that can cause errors in your scripts and
protected keywords for future use by ActionScript or the ECMAScript (ECMA-262) edition
4 draft language specifications see Avoiding reserved words and language constructs
on page 668.

To learn the names of language constructs, refer to the ActionScript 2.0 Language Reference.

About statements
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.104 Syntax and Language Fundamentals
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. For
information on writing and formatting events, see Chapter 9, “Handling Events,” on
page 291.
For more information on each statement, see the following topics:
■ “About compound statements” on page 104
■ “About conditions” on page 105
■ “Repeating actions using loops” on page 115

About compound statements
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.
For more information on using braces, see “Curly braces” on page 90.About statements 105

About conditions
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.

For more information on conditions that you can use, and how to write them, see the
following topics:

■ “About writing conditions” on page 105
■ “Using the if statement” on page 106
■ “Using the if..else statement” on page 107
■ “Using the if..else if statement” on page 108
■ “Using a switch statement” on page 109
■ “Using try..catch and try..catch..finally statements” on page 111
■ “About the conditional operator and alternative syntax” on page 114

About writing conditions
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.
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");
{
T I P
To optimize your code’s performance, check for the most likely conditions first.106 Syntax and Language Fundamentals

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. For more information on switch statements, see “Using a
switch statement” on page 109.
Refer to the following sections to learn how to write different kinds of conditions in your
ActionScript applications.


Using the if statement
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.About statements 107
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
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.108 Syntax and Language Fundamentals
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
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 t o us e 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"); {About statements 109 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
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.110 Syntax and Language  Fundamentals.
      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;About statements 111
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
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.
You wr it e try..catch and try..catch..finally statements using the following format:
// try-catch
try {
// statements
} catch (myError) {
// statements
{
// try-catch-finally
try {
// statements
N O T E
The finally block executes even if the try block exits using a return statement112 Syntax and Language Fundamentals
} 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.About statements 113
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. For more information on creating custom classes, see Chapter 6, “Classes,”
on page 187.114 Syntax and Language Fundamentals
About the conditional operator and alternative syntax

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.About statements 115
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 more information on operator precedence, see
“About operator precedence and associativity” on page 140.
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

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.116 Syntax and Language Fundamentals
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);
For more information on the while statement, see “Using while loops” on page 122.About statements 117
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});
{
For more information on the for statement, see “Using for loops” on page 119.
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);
{
{118 Syntax and Language Fundamentals
For more information on the for..in statement, see “Using for..in loops” on page 120.
For more information on each statement, see the individual sections that follow in this
chapter, such as “Using while loops” on page 122, and their respective entries in the

ActionScript 2.0 Language Reference.

About creating and ending loops
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? W A R N I N G Iterations in Flash execute very quickly in the Flash Player, but loops depend heavily on the processor. The more iterations a loop has and the more statements executed within each block, the more processor resources will be consumed. Poorly written loops can cause performance problems and stability issues.About statements 119 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. For more information on controlling loops, see “Using a switch statement” on page 109. Using for loops 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.120 Syntax and Language Fundamentals

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. Remember to include a space following each expression in a for statement. For more information, see the for statement in the ActionScript 2.0 Language Reference. Using for..in loops 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 an unpredictable 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]);

{About statements 121 This code outputs the following in the Output panel: three two one For more information on objects and properties, see “Object data type” on page 42. 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. For more information on writing class files, see Chapter 6, “Classes,” on page 187. For
more information, see the for..in statement in the ActionScript 2.0 Language Reference.

N O T E
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.
N O T E
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.122 Syntax and Language Fundamentals
Using while loops
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.About statements 123
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
For more information, see the while statement in the ActionScript 2.0 Language Reference.
About do..while loops
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. For more information on and examples of do..while statement, see the ActionScript 2.0 Language Reference.124 Syntax and Language Fundamentals Using nested loops in your ActionScript 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 125

About arrays
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).126 Syntax and Language Fundamentals
For more information on modifying arrays, see “About modifying arrays” on page 127. For
information on using arrays and about indexes, see “Using arrays” on page 126. For
information on adding and removing elements, see “About adding and removing elements”
on page 129. For information on the array access operator, see “Using dot and array access
operators” on page 145.

For a sample source file, array.fla, that illustrates array manipulation using ActionScript, see
the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress
the Samples zip file and navigate to the ActionScript2.0/Arrays folder to access the sample.
The code in the sample creates an array and sorts, adds, and removes items of two List
components.

No comments:

Post a Comment