• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

About variables

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. For more information on data typing, see “About assigning data types and strict data typing” on page 83 and “Assigning a data type” on page 84.

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. For more information on different kinds of variables and scope, see “About variables and scope” on page 99.

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; for more information, see “About data types” on page 74. 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.

For more information on variables, see the following topics:

About declaring variables

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. For more information on assigning data types, see “About assigning data types and strict data typing” on page 83.

About default values

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. For more information on creating and using variables, see “About variables” on page 89.

About assigning values

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

For more information on creating arrays and the array access operators, see “About arrays” on page 167 and “About using dot syntax to target an instance” on page 122.

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

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.


For more information on using operators in your ActionScript, see “About operators” on page 180.

About naming variables

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. For more information on literals, see “About literals” on page 134.

  • A variable must be unique within its scope (see “About variables and scope” on page 99).

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

For recommended coding conventions for naming variables, see “Naming variables” on page 750.

Using variables in an application

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. For more information on writing expressions, see Chapter 5, “Syntax and Language Fundamentals,” on page 117.

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

For information on passing a variable by reference, see “Passing a variable by reference” on page 97.

Passing a variable by reference

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.

For more information on arrays, see “About arrays” on page 167.

About variables and scope

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, see “About scope and targeting” on page 127.

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 Chapter 5, “About scope and targeting,” on page 127.

Note

ActionScript 2.0 classes that you create support public, private, and static variable scopes. For more information, see “About class members” on page 256 and “Controlling member access in your classes” on page 278.


You cannot strict type global variables. For information and a workaround, see “Global variables” on page 99.

Global variables

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. For more information, see Chapter 17, “Understanding Security,” on page 691.

Timeline variables

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. For example, if you put the code var myNum:Number = 15; in Frame 20, any scripts attached to a frame before Frame 20 cannot access myNum and are undefined instead of containing the value 15.

Local variables

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. For more information, see “About assigning data types and strict data typing” on page 83.

About loading variables

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 Chapter 16, “Working with External Data,” on page 647.

You can use variables in different ways in a SWF file, depending on what you need the variables for. For more information, see the following topics:

Using variables from the URL

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.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="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.macromedia.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.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?myURL=http://
									weblogs.macromedia.com" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="urlvariables.swf?myURL=http://weblogs.macromedia.com"
  quality="high" 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.
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.macromedia.com

Replace it with the following text:

?myURL=http://weblogs.macromedia.com&myTitle=Macromedia+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, see the Flash TechNote, URL Encoding: Reading special characters from a text file.

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.macromedia.com&myTitle=Macromedia+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

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.macromedia.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.macromedia.com/">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="myflashvars.swf" FlashVars="myURL=http://
									weblogs.macromedia.com/" quality="high" bgcolor="#ffffff" width="550"
  height="400" name="myflashvars" align="middle"
  allowScriptAccess="sameDomain" type="application/x-shockwave-flash"
  pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>


					  

This code passes a single variable called myURL, which contains the string http://weblogs.macromedia.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.macromedia.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

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 Chapter 16, “Working with External Data,” on page 647.

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 (www.helpexamples.com/flash/params.txt) 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

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 Chapter 16, “Working with External Data,” on page 647.

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. For information on using URL variables, see “Using variables from the URL” on page 103. For information on FlashVars, see “Using FlashVars in an application” on page 106.

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

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint