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

 

What is Data and Data Types in Flash

About data

About data types

About primitive and complex data types

Boolean data type

MovieClip data type

null data type

Number data type

Object data type

String data type

Undefined data type

Void data type

About assigning data types and strict data typing

Assigning a data type

About type checking

About determining data type

About variables

About declaring variables

About default values

About assigning values

About operators and variables

About naming variables

Using variables in an application

Passing a variable by reference

About variables and scope

Pinning scripts in the Actions panel

Global variables

Timeline variables

Local variables

About loading variables

Using variables from the URL

Using FlashVars in an application

Loading variables from a server

Using variables in a project

Organizing data in objects

About casting

About casting objects

About data

TOP

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 define data 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.

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

TOP

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.

ActionScript has numerous basic data types that you will probably use frequently in your applications.

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.

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 built-in classes, see About top-level and built-in classes. For more information on creating custom classes, see Classes.

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.

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.

You can convert one data type to another at runtime using one of the following conversion functions: Array(), Boolean(), Number(), Object(), String().

You can find a sample source file, datatypes.fla, in the Samples folder on your hard disk, which shows you how to use data types in an application.

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

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

 

About primitive and complex data types

TOP

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.

Variables that contain primitive data types behave differently in certain situations than those containing complex types.

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.

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.

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).

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).

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.

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.

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.

You can find a sample source file, datatypes.fla, in the Samples folder on your hard disk, which shows you how to use data types in an application.

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

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

 

Boolean data type

TOP

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.

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

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);

 

MovieClip data type

TOP

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;

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();

};

 

null data type

TOP

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");

}

 

Number data type

TOP

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 (--).

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

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

TOP

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();

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";

 

String data type

TOP

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)

\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

Strings in ActionScript are immutable, just as they are in Java. Any operation that modifies a string returns a new string.

 

undefined data type

TOP

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

TOP

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 {}

 

About assigning data types and strict data typing

TOP

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. 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;

NOTE : Strict data typing is sometimes called strong typing a variable.

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.

You can find a sample source file, datatypes.fla, in the Samples folder on your hard disk, which shows you how to use data types in an application.

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

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

 

Assigning a data type

TOP

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 post-colon 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;

}

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 built-in objects when they are strictly typed.

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 */

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.

 

About type checking

TOP

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.

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");

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

TOP

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); // true

 

About variables

TOP

A variable is a container that holds information. The following ActionScript shows what a variable looks like in ActionScript:

var myVariable:Number = 10;

This variable holds a numerical value. The use of :Number in the previous code assigns the type of value that variable holds, called data typing.

The container (represented by the variable name) is always the same throughout your ActionScript, but the contents (the value) can change. You can change the value of a variable in a script as many times as you want. When you change the value of a variable while the SWF file plays, you can record and save information about what the user has done, record values that change as the SWF file plays, or evaluate whether a condition is true or false. You might need the variable to continually update while the SWF file plays, such as when a player's score changes in a Flash game. Variables are essential when you create and handle user interaction in a SWF file.

It's a good idea to assign a value to a variable the first time you declare the variable. Assigning an initial value is called initializing the variable, and it's often done on Frame 1 of the Timeline or from within a class that loads when the SWF file begins to play. There are different kinds of variables, which are affected by scope.

TIP : Initializing a variable helps you track and compare the variable's value as the SWF file plays.

NOTE : Flash Player 7 and later evaluate uninitialized variables differently than Flash Player 6 and earlier. If you have written scripts for Flash Player 6 and plan to write or port scripts for Flash Player 7 or later, you should be understand these differences to avoid unexpected behavior.

Variables can hold different types of data. The type of data that a variable contains affects how the variable's value changes when you assign that value in a script.

Typical types of information that you can store in a variable include a URL (String type), a user's name (String type), the result of a mathematical operation (Number type), the number of times an event occurred (Number type), or whether a user has clicked a particular button (Boolean type). Each SWF file and object instance (such as a movie clip) has a set of variables, with each variable having a value independent of variables in other SWF files or movie clips.

To view the value of a variable, use the trace() statement to send the value to the Output panel. Then, the value displays in the Output panel when you test the SWF file in the test environment. For example, trace(hoursWorked) sends the value of the variable hoursWorked to the Output panel in the test environment. You can also check and set the variable values in the Debugger in the test environment.

 

About declaring variables

TOP

You can declare variables on a frame in the timeline, directly on an object, or within an external class file.

Define variables using the var keyword and follow the variable naming conventions. You can declare a variable called firstName, as shown in the following example:

var firstName:String;

When you declare a variable, you assign a data type to the variable. In this case, you assign the String data type to the firstName variable.

 

About default values

TOP

A default value is the value that a variable contains before you set its value. You initialize a variable when you set its value for the first time. If you declare a variable, but do not set its value, that variable is uninitialized. The value of an uninitialized variable defaults to the value undefined.

 

About assigning values

TOP

You can define a value as the current contents of a variable. The value can be a strings, numbers, arrays, objects, XML, dates, or even custom classes that you create. Remember, you declare a variable in Flash using the var keyword. When you declare the variable, you also assign a data type to the variable. You can also assign a value to a variable, as long as the value matches the data type you assign to the variable.

The following example shows how you might create a variable called catName:

var catName:String;

After you declare the variable, you can assign a value to it. You might follow the previous line of ActionScript with this line:

catName = "Pirate Eye";

NOTE : Because Pirate Eye is a string, the value needs to be enclosed in straight quotes (quotation marks).

This example assigns the value of Pirate Eye to the catName variable. When you declare the variable, you can also assign a value to it instead of assigning it afterwards (as in the previous examples). You could set the catName variable when you declare it, as shown in the following example:

var catName:String = "Pirate Eye";

If you want to display the value of the catName variable in the test environment, you can use the trace() statement. This statement sends the value to the Output panel. You can trace the value of the catName variable and see that the actual value doesn't include the quotation marks by using the following ActionScript:

var catName:String = "Pirate Eye";

trace(catName); // Pirate Eye

Remember that the value you assign must match the data type that you assign to it (in this case, String). If you later try to assign a number to the catName variable, such as catName = 10, you will see the following error in the Output panel when you test the SWF file:

Type mismatch in assignment statement: found Number where String is required.

This error tells you that you attempted to set the wrong data type to a specified variable.

When you assign a numeric value to a variable, the quotation marks aren't necessary, as shown in the following code:

var numWrinkles:Number = 55;

If you want to change the value of numWrinkles later in your code, you can assign a new value using the following ActionScript:

numWrinkles = 60;

When you reassign a value to an existing variable, you don't need to use the var keyword or define the variable's data type (in this case, :Number).

If the value is numeric or Boolean (true or false), the value doesn't use straight quotes (quotation marks). Examples of numeric and Boolean values are shown in the following snippet:

var age:Number = 38;

var married:Boolean = true;

var hasChildren:Boolean = false;

In the previous example, the variable age contains an integer (nondecimal) value, although you could also use a decimal or floating-point value such as 38.4. Boolean variables (such as married or hasChildren) have only two possible values, true or false.

If you want to create an array and assign values to it, the format is slightly different, as shown in the following code:

var childrenArr:Array = new Array("Pylon", "Smithers", "Gil");

There is an alternative (shorthand) syntax for creating an array using array access operators, which use the bracket ([]) punctuators. You can rewrite the previous example as follows:

var childrenArr:Array = ["Pylon", "Smithers", "Gil"];

Similarly, you can create a new object called myObj. You can use either of the following ways to create a new object. The first (and longer) way to code an array is as follows:

var myObj:Object = new Object();

myObj.firstName = "Steve";

myObj.age = 50;

myObj.childrenArr = new Array("Mike", "Robbie", "Chip");

The second, shorthand way you can code the myObj array is as follows:

var myObj:Object = {firstName:"Steve", age:50, childrenArr:["Mike", "Robbie", "Chip"]};

As you see in this example, using the shorthand method can save a lot of typing and time, especially when you define instances of objects. It is important to be familiar with this alternate syntax because you will encounter it if you work in teams or when you work with third-party ActionScript code that you find, for example, on the Internet or in books.

NOTE : Not all variables need to be explicitly defined. Some variables are created by Flash automatically for you. For example, to find the dimensions of the Stage, you could use the values of the following two predefined values: Stage.width and Stage.height.

 

About operators and variables

TOP

You might wonder about the mathematical symbols in your code. These symbols are called operators in ActionScript. Operators calculate a new value from one or more values, and you use an operator to assign a value to a variable in your code. You use the equality (=) operator to assign a value to a variable:

var username:String = "Gus";

Another example is the addition (+) operator, which you use to add two or more numeric values to produce a new value. If you use the + operator on two or more string values, the strings will be concatenated. The values that operators manipulate are called operands.

When you assign a value, you use an operator to define a value to a variable. For example, the following script uses the assignment operator to assign a value of 7 to the variable numChildren:

var numChildren:Number = 7;

If you want to change the value of the numChildren variable, use the following code:

numChildren = 8;

NOTE : You don't need to use var because the variable has previously been defined.

 

About naming variables

TOP

Be careful when you start naming variables, because although they can have nearly any name, there are some rules. A variable's name must follow these rules:

  • A variable must be an identifier.

    NOTE : An identifier is the name of a variable, property, object, function, or method. The first character of an indentifier must be a letter, underscore (_), or dollar sign ($). Each subsequent character can be a number, letter, underscore, or dollar sign.

  • A variable cannot be a keyword or an ActionScript literal such as true, false, null, or undefined.

  • A variable must be unique within its scope.

  • A variable should not be any element in the ActionScript language, such as a class name.

If you don't follow the rules when you name a variable, you might experience syntax errors or unexpected results. In the following example, if you name a variable new and then test your document, Flash will generate a compiler error:

// This code works as expected.

var helloStr:String = new String();

trace(helloStr.length); // 0

// But if you give a variable the same name as a built-in class...

var new:String = "hello"; //error: Identifier expected

var helloStr:String = new String();

trace(helloStr.length); // undefined

The ActionScript editor supports code hints for built-in classes and for variables that are based on these classes. If you want Flash to provide code hints for a particular object type that you assign to a variable, you can strictly type the variable. Code hints provide tooltip-style syntax hints and a pop-up menu that helps you write your code quickly.

For example, type the following code:

var members:Array = new Array();

members.

As soon as you type the period (.) in the Actions panel, Flash displays a list of methods and properties available for Array objects.

 

Using variables in an application

TOP

In this section, you use variables in short code snippets of ActionScript. You need to declare and initialize a variable in a script before you can use it in an expression. Expressions are combinations of operands and operators that represent a value. For example, in the expression i+2, i and 2 are operands, and + is an operator.

If you do not initialize a variable before you use it in an expression, the variable is undefined and may cause unexpected results.

If you use an undefined variable, as shown in the following example, the variable's value in Flash Player 7 and later will be NaN, and your script might produce unintended results:

var squared:Number = myNum * myNum;

trace(squared); // NaN

var myNum:Number = 6;

In the following example, the statement that declares and initializes the variable myNum comes first, so squared can be replaced with a value:

var myNum:Number = 6;

var squared:Number = myNum * myNum;

trace(squared); // 36

Similar behavior occurs when you pass an undefined variable to a method or function, as shown next.

To compare undefined and defined variables being passed to a function:

  1. Drag a Button component to the Stage from the Components panel.

  2. Open the Property inspector and type bad_button into the Instance Name text box.

  3. Type the following code on Frame 1 of the Timeline.

    // Does not work

    function badClickListener(evt:Object):Void {

    getURL(targetUrl);

    var targetUrl:String = "http://www.adobe.com";

    }

    bad_button.addEventListener("click", badClickListener);

  4. Select Control > Test Movie, and notice that the button does not work (it doesn't open the web page).

  5. Drag another Button component onto the Stage. Select the button.

  6. Open the Property inspector, and type good_button into the Instance Name text box.

  7. Add the following ActionScript to Frame 1 of the Timeline (following the previous ActionScript you added):

    // Works

    function goodClickListener(evt:Object):Void {

    var targetUrl:String = "http://www.adobe.com";

    getURL(targetUrl);

    }

    good_button.addEventListener("click", goodClickListener);

  8. Select Control > Test Movie and click the second button you added to the Stage.

    This button properly opens the web page.

The type of data that a variable contains affects how and when the variable's value changes. Primitive data types, such as strings and numbers, are passed by value, which means the current value of the variable is used rather than a reference to that value. Examples of complex data types include the Array and Object data types.

In the following example, you set myNum to 15 and copy the value into otherNum. When you change myNum to 30 (in line 3 of the code), the value of otherNum remains 15 because otherNum doesn't look to myNum for its value. The otherNum variable contains the value of myNum that it receives (in line 2 of the code).

To use variables in your ActionScript:

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

  2. Select Frame 1 of the Timeline, and type the following code into the Actions panel:

    var myNum:Number = 15;

    var otherNum:Number = myNum;

    myNum = 30;

    trace(myNum); // 30

    trace(otherNum); // 15

    When you change myNum to 30 (in line 3 of the code), the value of otherNum remains 15 because otherNum doesn't look to myNum for its value. The otherNum variable contains the value of myNum that it receives (in line 2 of the code).

  3. Select Control > Test Movie to see the values display in the Output panel.

  4. Now add the following ActionScript after the code you added in step 2:

    function sqr(myNum:Number):Number {

    myNum *= myNum;

    return myNum;

    }

    var inValue:Number = 3;

    var outValue:Number = sqr(inValue);

    trace(inValue); // 3

    trace(outValue); // 9

    In the this code, the variable inValue contains a primitive value, 3, so the value passes to the sqr() function, and the returned value is 9. The value of the variable inValue does not change, although the value of myNum in the function changes.

  5. Select Control > Test Movie to see the values display in the Output panel.

The Object data type can contain such a large amount of complex information that a variable with this type doesn't hold an actual value; it holds a reference to a value. This reference is similar to an alias that points to the contents of the variable. When the variable needs to know its value, the reference asks for the contents and returns the answer without transferring the value to the variable.

 

Passing a variable by reference

TOP

Because the Array and Object data types hold a reference to a value instead of containing its actual value, you need be careful when you work with arrays and objects.

The following example shows how to pass an object by reference. When you create a copy of the array, you actually create only a copy of the reference (or alias) to the array's contents. When you edit the contents in the second array, you modify both the contents of the first and second array because they both point to the same value.

To pass an object by reference:

  1. Select File > New and then select Flash Document to create a new FLA file, and save it as copybyref.fla.

  2. Select Frame 1 of the Timeline, and type the following code into the Actions panel:

    var myArray:Array = new Array("tom", "josie");

    var newArray:Array = myArray;

    myArray[1] = "jack";

    trace(myArray); // tom,jack

    trace(newArray); // tom,jack

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

    This ActionScript creates an Array object called myArray that has two elements. You create the variable newArray and pass a reference to myArray. When you change the second element of myArray to jack, it affects every variable with a reference to it. The trace() statement sends tom,jack to the Output panel.

    NOTE : Flash uses a zero-based index, which means that 0 is the first item in the array, 1 is the second, and so on.

In the following example, myArray contains an Array object, so you pass the array to function zeroArray() by reference. The function zeroArray() accepts an Array object as a parameter and sets all the elements of that array to 0. It can modify the array because the array is passed by reference.

To pass an array by reference:

  1. Select File > New and then select Flash Document to create a new FLA file, and save it as arraybyref.fla.

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

    function zeroArray (theArr:Array):Void {

    var i:Number;

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

    theArr[i] = 0;

    }

    }

    var myArr:Array = new Array();

    myArr[0] = 1;

    myArr[1] = 2;

    myArr[2] = 3;

    trace(myArr); // 1,2,3

    zeroArray(myArr);

    trace(myArr); // 0,0,0

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

The first trace() statement in this ActionScript displays the original contents of the myArray array (1,2,3). After you call the zeroArray() function and pass a reference to the myArray array, each of the array's values are overwritten and set to zero. The subsequent trace() statement displays the new contents of the myArray array (0,0,0). Because you pass the array by reference and not by value, you don't need to return the updated contents of the array from within the zeroArray() function.

 

About variables and scope

TOP

A variable's scope refers to the area in which the variable is known (defined) and can be referenced. The area in which the variable is known might be within a certain timeline or inside a function, or it might be globally known throughout the entire application.For more information about scope.

Understanding variable scope is important when you develop Flash applications with ActionScript. Scope indicates not only when and where you can refer to variables but also for how long a particular variable exists in an application. When you define variables in the body of a function, they cease to exist as soon as the specified function ends. If you try to refer to objects in the wrong scope or to variables that have expired, you get errors in your Flash documents, which lead to unexpected behavior or broken functionality.

There are three types of variable scopes in ActionScript:

  • Global variables and functions are visible to every timeline and scope in your document. Therefore, a global variable is defined in all areas of your code.

  • Timeline variables are available to any script on that timeline.

  • Local variables are available within the function body in which they are declared (delineated by curly braces). Therefore, local variables are only defined in a part of your code.

For guidelines on using scope and variables, see About scope and targeting.

NOTE :  ActionScript 2.0 classes that you create support public, private, and static variable scopes.

 

Pinning scripts in the Actions panel

TOP

If you don't centralize your code within a FLA file in one location (discussed in Organizing ActionScript code) or if you're using behaviors (see About behaviors), you can pin multiple scripts in the Actions panel to make it easier to move among them. To pin a script means that you can keep the location of the code open in the Actions panel, and easily click between each open script.

In the following figure, the script associated with the current location on the timeline is on Frame 1 of the layer named Cleanup. (The tab at the far left always follows your location along the timeline.) That script is also pinned (it is shown as the right-most tab). Two other scripts are pinned: one on Frame 1 and the other on Frame 15 of the layer named Intro. You can move among the pinned scripts by clicking on the tabs or by using keyboard shortcuts, such as Control+Shift+. (period). Moving among pinned scripts does not change your current position on the timeline. As you can see in the following figure, multiple scripts are open in the Actions panel, and you can click each tab to move between the scripts.

TIP : If the content in the Script pane doesn't change to reflect the location that you select on the timeline, the Script pane is probably showing a pinned script. Click the left tab at the lower left of the Script pane to show the ActionScript associated with your location along the timeline.

To pin a script:

  1. Position your mouse pointer on the Timeline so the script appears in a tab at the lower left of the Script pane in the Actions panel.

  2. Do one of the following:

    • Click the pushpin icon to the right of the tab.

    • Right-click (Windows) or Control-click (Macintosh) on the tab, and select Pin Script.

    • Select Pin Script from the pop-up menu (at the upper right of the Actions panel).

    • With the mouse pointer focused in the Script pane, press Control+= (equal sign) in Windows or Command+= on the Macintosh.

To unpin one or more scripts, do one of the following:

  • If a pinned script appears in a tab at the lower left of the Script pane in the Actions panel, click the pushpin icon on the right of the tab.

  • Right-click (Windows) or Control-click (Macintosh) on a tab, and select Close Script or Close All Scripts.

  • Select Close Script or Close All Scripts from the pop-up menu (at the upper right of the Actions panel).

  • With the mouse pointer focused in the Script pane, press Control+-(minus sign) in Windows or Command+- on Macintosh.

To use keyboard shortcuts with pinned scripts:

  • You can use the following keyboard shortcuts to work with pinned scripts:

Action

Windows shortcut key

Macintosh shortcut key

Pin script

Control+= (equal sign)

Command+=

Unpin script

Control+- (minus sign)

Command+-

Move focus to tab on the right

Control+Shift+. (period)

Command+Shift+.

Move focus to tab on the left

Control+Shift+, (comma)

Command+Shift+,

Unpin all scripts

Control+Shift+- (minus)

Command+Shift+-

Global variables

TOP

Global variables and functions are visible to every timeline and scope in your document. To declare (or create) a variable with global scope, use the _global identifier before the variable name and do not use the var = syntax. For example, the following code creates the global variable myName:

var _global.myName = "George"; // Incorrect syntax for global variable

_global.myName = "George"; // Correct syntax for global variable

However, if you initialize a local variable with the same name as a global variable, you don't have access to the global variable while you are in the scope of the local variable, as shown in the following example:

_global.counter = 100; // Declares global variable

trace(counter); // Accesses the global variable and displays 100

function count():Void {

for (var counter:Number = 0; counter <= 2; counter++) { // Local variable

trace(counter); // Accesses local variable and displays 0 through 2

}

}

count();

trace(counter); // Accesses global variable and displays 100

This example simply shows that the global variable is not accessed in the scope of the count() function. However, you could access the global-scoped variable if you prefix it with _global. For example, you could access it if you prefix the counter with _global as shown in the following code:

trace(_global.counter);

You cannot assign strict data types to variables that you create in the _global scope, because you have to use the var keyword when you assign a data type. For example, you couldn't do:

_global.foo:String = "foo"; //syntax error

var _global.foo:String = "foo"; //syntax error

The Flash Player version 7 and later security sandbox enforces restrictions when accessing global variables from SWF files loaded from separate security domains.

 

Timeline variables

TOP

Timeline variables are available to any script on that particular timeline. To declare timeline variables, use the var statement and initialize them in any frame in the timeline. The variable is available to that frame and all following frames, as shown in the following example.

To use timeline variables in a document:

  1. Create a new Flash document, and name it timelinevar.fla.

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

    var myNum:Number = 15; /* initialized in Frame 1, so it's available to all frames */

  3. Select Frame 20 of the Timeline.

  4. Select Insert > Timeline > Blank Keyframe.

  5. With the new keyframe selected, type the following ActionScript into the Actions panel:

    trace(myNum);

  6. Select Control > Test Movie to test the new document.

    The value 15 appears in the Output panel after approximately a second. Because Flash documents loop by default, the value 15 continually traces in the Output panel every time the playhead reaches Frame 20 in the Timeline. To stop the looping action, add stop(); after the trace() statement.

You must declare a timeline variable before trying to access it in a script.

 

Local variables

TOP

When you use the var statement inside a function block, you declare local variables. When you declare a local variable within a function block (also called function definition), it is defined within the scope of the function block, and expires at the end of the function block. Therefore, the local variable only exists within that function.

For example, if you declare a variable named myStr within a function named localScope, that variable will not be available outside of the function.

function localScope():Void {

var myStr:String = "local";

}

localScope();

trace(myStr); // Undefined, because myStr is not defined globally

If the variable name you use for your local variable is already declared as a timeline variable, the local definition takes precedence over the timeline definition while the local variable is in scope. The timeline variable will still exist outside of the function. For example, the following code creates a timeline string variable named str1, and then creates a local variable of the same name inside the scopeTest() function. The trace statement inside the function generates the local definition of the variable, but the trace statement outside the function generates the timeline definition of the variable.

var str1:String = "Timeline";

function scopeTest():Void {

var str1:String = "Local";

trace(str1); // Local

}

scopeTest();

trace(str1); // Timeline

In the next example, you can see how certain variables live only for the life of a specific function and can generate errors if you try to refer to the variable outside the scope of that function.

To use local variables in an application:

  1. Create a new Flash document.

  2. Open the Actions panel (Window > Actions) and add the following ActionScript to Frame 1 of the Timeline:

    function sayHello(nameStr:String):Void {

    var greetingStr:String = "Hello, " + nameStr;

    trace(greetingStr);

    }

    sayHello("world"); // Hello, world

    trace(nameStr); // undefined

    trace(greetingStr); // undefined

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

    Flash displays the string "Hello, world" in the Output panel and displays undefined for the values of nameStr and greetingStr because the variables are no longer available in the current scope. You can only reference nameStr and greetingStr in the execution of the sayHello function. When the function exits, the variables cease to exist.

The variables i and j are often used as loop counters. In the following example, you use i as a local variable; it exists only inside the initArray() function:

var myArr:Array = new Array();

function initArray(arrayLength:Number):Void {

var i:Number;

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

myArr[i] = i + 1;

}

}

trace(myArr); // <blank>

initArray(3);

trace(myArr); // 1,2,3

trace(i); // undefined

NOTE : It's also common to see the following syntax for a for loop: for (var i:Number = 0; i < arrayLength; i++) {...}.

This example displays undefined in the Flash test environment because the variable i isn't defined in the main timeline. It exists only in the initArray() function.

You can use local variables to help prevent name conflicts, which can cause unexpected results in your application. For example, if you use age as a local variable, you could use it to store a person's age in one context and the age of a person's child in another context. There is no conflict in this situation because you are using these variables in separate scopes.

It's good practice to use local variables in the body of a function so the function can act as an independent piece of code. You can change a local variable only within its own block of code. If an expression in a function uses a global variable, code or events outside the function can change its value, which changes the function.

You can assign a data type to a local variable when you declare it, which helps prevent assigning the wrong type of data to an existing variable.

 

About loading variables

TOP

In the following sections, you load variables from the server in different ways or into a document from a URL string or FlashVars (you can use FlashVars to pass variables into Flash) in your HTML code. These practices demonstrate that there are several ways to use variables outside a SWF file.

You can find more information on loading variables (such as name/value pairs) in Working with External Data.

You can use variables in different ways in a SWF file, depending on what you need the variables for.

 

Using variables from the URL

TOP

When you develop an application or simple example in Flash, you might want to pass values from an HTML page into your Flash document. The passed values are sometimes known as the query string, or URL-encoded variables. URL variables are useful if you want to create a menu in Flash, for example. You can initialize the menu to show the correct navigation by default. Or you can build an image viewer in Flash and define a default image to show on the website.

To use URL variables in a document:

  1. Create a Flash document, and name it urlvariables.fla.

  2. Select File > Save As, and save the document on your desktop.

  3. Select Frame 1 of the Timeline, and add the following code in the Actions panel:

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

    myTxt.autoSize = "left";

    myTxt.text = _level0.myURL;

  4. Select Control > Test Movie to test the SWF file in Flash Player.

    The text field displays undefined. If you want to make sure the variables are properly defined before you proceed, you need to check for the existence of the variables in Flash. You can do this by checking to see if they are undefined.

  5. To check to see if the variable is defined, modify the ActionScript you added to the Actions panel in step 3 to match the following code. Add the code that appears in bold:

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

    myTxt.autoSize = "left";

    if (_level0.myURL == undefined) {

    myTxt.text = "myURL is not defined";

    } else {

    myTxt.text = _level0.myURL;

    }

    When you publish your Flash document, an HTML document is created by default in the same directory as the SWF file. If an HTML file was not created, select File > Publish settings, and make sure you select HTML in the Formats tab. Then publish your document again.

    The following code demonstrates the HTML in the document that is responsible for embedding a Flash document in an HTML page. You need to look at this HTML to understand how URL variables work in the following step (where you add additional code for URL variables).

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"

    codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="550" height="400" id="urlvariables" align="middle">

    <param name="allowScriptAccess" value="sameDomain" />

    <param name="movie" value="urlvariables.swf" />

    <param name="quality" value="high" />

    <param name="bgcolor" value="#ffffff" />

    <embed src="urlvariables.swf" quality="high" bgcolor="#ffffff" width="550" height="400" name="urlvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />

    </object>

  6. To pass variables from the generated HTML document to your Flash document, you can pass variables after the path and filename (urlvariables.swf). Add the bold text to the HTML file that was generated on your desktop.

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.adobe.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="550" height="400" id="urlvariables" align="middle">

    <param name="allowScriptAccess" value="sameDomain" />

    <param name="movie" value="urlvariables.swf?myURL=http://weblogs.adobe.com" />

    <param name="quality" value="high" />

    <param name="bgcolor" value="#ffffff" />

    <embed src="urlvariables.swf?myURL=http://weblogs.adobe.com" quality="high" bgcolor="#ffffff" width="550" height="400" name="urlvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />

    </object>

  7. If you want to pass multiple variables to Flash, you need to separate the name/values pairs with an ampersand (&). Find the following code from step 6:

    ?myURL=http://weblogs.adobe.com

    Replace it with the following text:

    ?myURL=http://weblogs.adobe.com&myTitle=Adobe+News+Aggregator

    Remember, you need to make the same changes to both the object tag and the embed tag to maintain consistency between all browsers. You might notice that the words are separated by + punctuators. The words are separated this way because the values are URL-encoded and the + punctuator represents a single blank space.

    NOTE : For a list of common URL-encoded special characters.

    Because the ampersand (&) serves as a delimiter for different name/value pairs, if the values you are passing contain ampersands, unexpected results might occur. Given the nature of name/value pairs and parsing, if you had the following values being passed to Flash:

    my.swf?name=Ben+&+Jerry&flavor=Half+Baked

    Flash would build the following variables (and values) into the root scope:

    'name': 'Ben ' (note space at end of value)

    ' Jerry': '' (note space at beginning of variable name and an empty value)

    'flavor': 'Half Baked'

    To avoid this, you need to escape the ampersand (&) character in the name/value pair with its URL-encoded equivalent (%26).

  8. Open the urlvariables.html document, and find the following code:

    ?myURL=http://weblogs.adobe.com&myTitle=Adobe+News+Aggregator

    Replace it with the following code:

    ?myURL=Ben+%26+Jerry&flavor=Half+Baked

  9. Save the revised HTML, and test your Flash document again.

    You see that Flash created the following name/value pairs.

    'name': 'Ben & Jerry'

    'flavor': 'Half Baked'

    NOTE : All browsers will support string sizes as large as 64K (65535 bytes) in length. FlashVars must be assigned in both the object and embed tags in order to work on all browsers.

 

Using FlashVars in an application

TOP

Using FlashVars to pass variables into Flash is similar to passing variables along the URL in the HTML code. With FlashVars, instead of passing variables after the filename, variables are passed in a separate param tag as well as in the embed tag.

To use FlashVars in a document:

  1. Create a new Flash document, and name it myflashvars.fla.

  2. Select File > Publish Settings and make sure that HTML is selected, and then click OK to close the dialog box.

  3. Add the following ActionScript to Frame 1 of the main Timeline:

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

    myTxt.autoSize = "left";

    if (_level0.myURL == undefined) {

    myTxt.text = "myURL is not defined";

    } else {

    myTxt.text = _level0.myURL;

    }

    NOTE : By default, HTML code publishes to the same location as myflashvars.fla.

  4. Select File > Publish to publish the SWF and HTML files.

  5. Open the directory containing the published files (where you saved myflashvars.fla on your hard drive) and open the HTML document (myflashvars.html by default) in an HTML editor such as Dreamweaver or Notepad.

  6. Add the code that appears in bold below, so your HTML document matches the following:

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"

    codebase="http://fpdownload.adbobe.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="550" height="400" id="myflashvars" align="middle">

    <param name="allowScriptAccess" value="sameDomain" />

    <param name="movie" value="myflashvars.swf" />

    <param name="FlashVars" value="myURL=http://weblogs.adobe.com/">

    <param name="quality" value="high" />

    <param name="bgcolor" value="#ffffff" />

    <embed src="myflashvars.swf" FlashVars="myURL=http://weblogs.adobe.com/" quality="high" bgcolor="#ffffff" width="550" height="400"

    name="myflashvars" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash"

    pluginspage="http://www.adobe.com/go/getflashplayer" />

    </object>

    This code passes a single variable called myURL, which contains the string

    http://weblogs.adobe.com. When the SWF file loads, a property named myURL is created in the _level0 scope. One of the advantages of using FlashVars or passing variables along the URL is that the variables are immediately available in Flash when the SWF file loads. This means you don't have to write any functions to check if the variables have finished loading, which you would need to do if you loaded variables using LoadVars or XML.

  7. Save your changes to the HTML document, and then close it.

  8. Double click myflashvars.html to test the application.

    The text http://weblogs.adobe.com, a variable in the HTML file, appears in the SWF file.

NOTE : All browsers will support string sizes as large as 64K (65,535 bytes) in length. FlashVars must be assigned in both the object and embed tags in order to work on all browsers.

 

Loading variables from a server

TOP

There are several ways to load variables into Flash from external sources (such as text files, XML documents, and so on). You can find much more information on loading variables, including name/value pairs.

In Flash, you can easily load variables using the LoadVars class, as shown in the next example.

To load variables from a server:

  1. Create a new Flash document.

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

    var my_lv:LoadVars = new LoadVars();

    my_lv.onLoad = function(success:Boolean):Void {

    if (success) {

    trace(this.dayNames); // Sunday,Monday,Tuesday,...

    } else {

    trace("Error");

    }

    }

    my_lv.load("http://www.helpexamples.com/flash/params.txt");

    This code loads a text file from a remote server and parses its name/value pairs.

    TIP : Download or view the text file in a browser if you want to know how the variables are formatted.

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

    If the file successfully loads, the complete event is called and the Output panel displays the value of dayNames. If the text file cannot be downloaded, the success argument is set to false and the Output panel displays the text Error.

 

Using variables in a project

TOP

When you build animations or applications with Flash, there are very few situations in which you don't need to use any kind of variable in your project. For example, if you build a login system, you might need variables to determine whether the user name and password are valid, or whether they are filled in at all.

You can find more information on loading variables (such as name/value pairs) in Working with External Data.

In the following example, you use variables to store the path of an image you are loading with the Loader class, a variable for the instance of the Loader class, and a couple of functions that are called depending on whether the file is successfully loaded or not.

To use variables in a project:

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

  2. Select Frame 1 of the Timeline, and add the following ActionScript to the Actions panel:

    /* Specify default image in case there wasn't a value passed using FlashVars. */

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

    if (_level0.imgURL != undefined) {

    // If image was specified, overwrite default value.

    imgUrl = _level0.imgURL;

    }

    this.createEmptyMovieClip("img_mc", 10);

    var mclListener:Object = new Object();

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

    target_mc._x = (Stage.width - target_mc._width) / 2;

    target_mc._y = (Stage.height - target_mc._height) / 2;

    }

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

    target_mc.createTextField("error_txt", 1, 0, 0, 100, 20);

    target_mc.error_txt.autoSize = "left";

    target_mc.error_txt.text = "Error downloading specified image;\n\t" + target_mc._url;

    }

    var myMCL:MovieClipLoader = new MovieClipLoader();

    myMCL.addListener(mclListener);

    myMCL.loadClip(imgUrl, img_mc);

    The first line of code specifies the image that you want to dynamically load into your Flash document. Next, you check whether a new value for imgURL was specified using FlashVars or URL-encoded variables. If a new value was specified, the default image URL is overwritten with the new value.

    The next couple of lines of code define the MovieClip instance, and a Listener object for the future MovieClipLoader instance. The MovieClipLoader's Listener object defines two event handlers, onLoadInit and onLoadError. The handlers are invoked when the image successfully loads and initializes on the Stage, or if the image fails to load. Then you create a MovieClipLoader instance, and use the addListener() method to add the previously defined listener object to the MovieClipLoader. Finally, the image is downloaded and triggered when you call the MovieClipLoader.loadClip() method, which specifies the image file to load and the target movie clip to load the image into.

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

    Because you're testing the Flash document in the authoring tool, no value for imgUrl will be passed by FlashVars or along the URL, and therefore the default image displays.

  4. Save the Flash document and select File > Publish to publish the file as a SWF and HTML document.

    NOTE : Make sure that Flash and HTML are both selected in the Publish Settings dialog box. Select File > Publish Settings and then click the Formats tab. Then, select both options.

  5. If you test your document in the Flash tool (select Control > Test Movie) or in a local browser (File > Publish Preview > HTML), you will see that the image centers itself both vertically and horizontally on the Stage.

  6. Edit the generated HTML document in an editor (such as Dreamweaver or Notepad), and modify the default HTML to match the following text:

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"

    codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="550" height="400" id="urlvariables" align="middle">

    <param name="allowScriptAccess" value="sameDomain" />

    <param name="movie" value="urlvariables.swf" />

    <param name="FlashVars" value="imgURL=http://www.helpexamples.com/flash/images/image2.jpg">

    <param name="quality" value="high" />

    <param name="bgcolor" value="#ffffff" />

    <embed src="urlvariables.swf" quality="high" FlashVars="imgURL=http://www.helpexamples.com/flash/images/image2.jpg" bgcolor="#ffffff" width="550" height="400" name="urlvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />

    </object>

  7. Test the HTML document to see the changes. An image that you specify in the HTML code appears in the SWF file.

    To modify this example to use your own images, you would modify the FlashVars value (the string inside the double quotes).

 

Organizing data in objects

TOP

You might already be used to objects that you place on the Stage. For example, you might have a MovieClip object on the Stage, and this object contains other movie clips inside it. Text fields, movie clips, and buttons are often called objects when you place them on the Stage.

Objects, in ActionScript, are collections of properties and methods. Each object has its own name, and it is an instance of a particular class. Built-in objects are from classes that are predefined in ActionScript. For example, the built-in Date class provides information from the system clock on the user's computer. You can use the built-in LoadVars class to load variables into your SWF file.

You can also create objects and classes using ActionScript. You might create an object to hold a collection of data, such as a person's name, address. and telephone number. You might create an object to hold color information for an image. Organizing data in objects can help keep your Flash documents more organized. For general information on creating a custom class to hold a collection of methods and properties.

There are several ways to create an object in ActionScript. The next example creates simple objects in two different ways, and then loops over the contents of those objects.

To create simple objects in Flash:

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

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

    // The first way

    var firstObj:Object = new Object();

    firstObj.firstVar = "hello world";

    firstObj.secondVar = 28;

    firstObj.thirdVar = new Date(1980, 0, 1); // January 1, 1980

    This code, which is one way to create a simple object, creates a new object instance and defines a few properties within the object.

  3. Now enter the following ActionScript after the code you entered in step 2.

    // The second way

    var secondObj:Object = {firstVar:"hello world", secondVar:28, thirdVar:new Date(1980, 0, 1)};

    This is another way of creating an object. Both objects are equivalent. This code above creates a new object and initializes some properties using the object shorthand notation.

  4. To loop over each of the previous objects and display the contents of objects, add the following ActionScript on Frame 1 of the Timeline (after the code you've already entered):

    var i:String;

    for (i in firstObj) {

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

    }

  5. Select Control > Test Movie, and the following text appears in the Output panel:

    firstVar: hello world

    secondVar: 28

    thirdVar: Tue Jan 1 00:00:00 GMT-0800 1980

You can also use arrays to create objects. Instead of having a series of variables such as firstname1, firstname2, and firstname3 to represent a collection of variables, you can make an array of objects to represent the same data. This technique is demonstrated next.

To use an array to create an object:

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

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

    var usersArr:Array = new Array();

    usersArr.push({firstname:"George"});

    usersArr.push({firstname:"John"});

    usersArr.push({firstname:"Thomas"});

    The benefit of organizing variables into arrays and objects is that it becomes much easier to loop over the variables and see the values, as shown in the following step.

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

    var i:Number;

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

    trace(usersArr[i].firstname); // George, John, Thomas

    }

  4. Select Control > Test Movie, and the following text appears in the Output panel:

    George

    John

    Thomas

The following example presents another way to loop over objects. In this example, an object is created and looped over using a for..in loop, and each property appears in the Output panel:

var myObj:Object = {var1:"One", var2:"Two", var3:18, var4:1987};

var i:String;

for (i in myObj) {

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

}

//outputs the following:

/*

var1: One

var2: Two

var3: 18

var4: 1987

*/

 

About casting

TOP

ActionScript 2.0 lets you cast one data type to another. Casting an object to a different type means you convert the value that the object or variable holds to a different type.

The results of a type cast vary depending on the data types involved. To cast an object to a different type, you wrap the object name in parentheses (()) and precede it with the name of the new type. For example, the following code takes a Boolean value and casts it to an integer.

var myBoolean:Boolean = true;

var myNumber:Number = Number(myBoolean);

 

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

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