One Part of the Sum: ActionScript Variables


In any scripting or programming language, you will need some type of "memory" device — something that can remember the values and properties of objects or significant data. This type of memory device is referred to as a variable.

Variables are named storage places for changeable pieces of data (numbers and letters, for starters). One of the first obstacles for designers learning a scripting language is the concept that variable names in and of themselves have no meaning or value to the computer. Remember that the computer can't perform anything unless you tell it to. Even though any given scripting language has a certain set of built-in properties and functions, variables can simplify your scripting workload by creating shortcuts or aliases to other elements of the ActionScript language. One prime example of a "shortcut" variable is the pathname to a deeply nested Movie Clip instance, such as:

 _root.birdAnim.birdHouse.birdNest.birdEgg 

truncated to a variable named mcEgg as:

 var mcEgg = _root.birdAnim.birdHouse.birdNest.birdEgg; 

If you wanted to declare mcEgg in ActionScript 2.0 code, you would use the following syntax, which types the mcEgg variable as a MovieClip object:

 var mcEgg:MovieClip = _root.birdAnim.birdHouse.birdNest.birdEgg; 

Once mcEgg is declared and given a value, you can reuse it without referring to the lengthy path name, as in:

 with(mcEgg){     gotoAndPlay("start"); } 

The important concept here is that you could just as easily have given mcEgg a different name, such as myPath, or robPath, or whatever word(s) you'd like to use. As long as the syntax and formatting of the expression is correct, you have nothing to worry about.

Another example of a variable that stores path information is the URL to a Web resource, such as a server-side script. Oftentimes, you may have different server URLs for testing and deployment. Instead of changing the URL in every action of the Flash document, you can use a variable name. That way, you only need to change your variable's value once. In the following sample code, a variable named serverURL is set to the actual URL you want to access. You then refer to that serverURL name in other actions, such as getURL().

 var serverURL = "http://www.flashsupport.com/"; getURL(serverURL); 

Note 

Variables in ActionScript are "typed," meaning that their value is explicitly set to be either a string, number, Boolean, or object. When working with variables, you must therefore know what data type the value is. We discuss data typing in Chapter 26, "Using Functions and Arrays."

Variables in ActionScript are attached to the timeline of the movie or Movie Clip instance on which they are created. If you create a variable x on the Main Timeline, that variable is available for other scripting actions on that timeline. However, from other Movie Clip timelines, the variable is not directly accessible. To access the value of a variable on another timeline (such as a Movie Clip instance), enter the target path to the clip instance in which the variable resides, a dot (.); then enter the variable name. For instance, this statement sets the variable foo to be equal to the value of the variable hitCount in the Movie Clip instance named mcBall:

 var foo = mcBall.hitCount; 

This statement, on the other hand, sets the variable foo to be equal to the value of a variable named hitCount on the Main Timeline:

 var foo = _root.hitCount; 

Tip 

Variables in ActionScript 1.0 are not case-sensitive and cannot start with a number. Variables in ActionScript 2.0 are case-sensitive.

Flash Player 6 introduced a new location to store variables, independent of any timeline: _global. You can access global variables from any object or timeline in the Flash movie — hence the name global. You only need to specify the _global path to assign a value to the global variable. To read a global variable, you simply specify the name. For example, on frame 1 of the Main Timeline, you can specify the following ActionScript in the Actions panel:

 _global.firstName = "George"; 

Then, if you wanted to use the firstName variable within a Movie Clip instance's timeline, you simply refer to the variable firstName. The following code will insert the firstName variable into a TextField object named user. This code would be placed inside of a Movie Clip symbol containing the TextField object:

 user.text = firstName; 

Even though the _global path is not specified, Flash Player 6 or 7 looks for a variable named firstName on the current timeline. If a variable by that name does not exist on the current timeline, Flash Player 6 looks in _global for the variable and returns any value for that variable.

Caution 

You need to publish your Flash documents as Flash Player 6 or higher movies to use the _global path. The global namespace can be used in ActionScript 1.0 or 2.0. Also, many experienced Flash developers frown upon the use of _global within a Flash document; overuse or overreliance on global variables can result in code that is difficult to debug. Why? Because the variable is global, you don't necessary know which element is setting a new value to the global variable, because the variable is available everywhere. By localizing your variables to custom objects and classes in proper object-oriented programming, you can manage the storage of information within your Flash movies more easily.

String Literals

In programmer speak, a string is any combination of alphanumeric characters. By themselves, they have no meaning. It is up to you to assign something meaningful to them. For example, giving a variable the name firstName doesn't mean much. You need to assign a value to the variable firstName to make it meaningful, and you can do something with it. For example, if firstName = "Susan", you could make something specific to "Susan" happen.

You can also use much simpler name/value pairs, such as i=0, to keep track of counts. If you want a specific Movie Clip animation to loop only three times, you can increment the value of i by 1 (for example, i=i+1, i+=1, and i++ all do the same thing) each time the animation loops back to the start. Then, you can stop the animation when it reaches the value of 3.

Expressions

Flash uses the term expression to refer to two separate kinds of code fragments in ActionScript. An expression is either a phrase of code used to compare values in a Conditional or a Loop (these are known as conditional expressions), or a snippet of code that is interpreted at run time (these are known as numeric expressions and string expressions). We discuss conditional expressions later in this chapter.

Numeric and string expressions are essentially just segments of ActionScript code that are dynamically converted to their calculated values when a movie runs. For instance, suppose you have a variable, y, set to a value of 3. In the statement x=y+1, the y+1 on the right side of the equal sign is an expression. Hence, when the movie runs, the statement x=y+1 actually becomes x=4, because the value of y (which is 3) is retrieved (or "interpreted") and the calculation 3+1 is performed. Numeric and string expressions are an extremely potent part of ActionScript because they permit most of the parameters used in actions to be based on mathematical calculations and external variables rather than requiring fixed information. Consider these two examples:

  • The parameter of a gotoAndPlay() action could be set as an expression that returns a random number in a certain range, sending the movie to a random frame:

     this.gotoAndPlay(Math.round(Math.random()*100)); 

  • The URL option in a getURL() action could be made up of a variable that indicates a server name and a literal string, which is the file path:

     var serverName = "http://localhost/"; var filePath = "resources/showRecent.cfm"; getURL(serverName + filePath); 

As we mentioned in an earlier section, to change all the URLs in your movie from a staging server to a live server, you'd just have to change the value of the server variable. So, to change the latter example's code for a live Web server, you'd simply change the serverName variable, as the following code demonstrates:

 var serverName = "http://www.flashsupport.com/"; 

All of the other lines of code would stay the same, because you only need to change the server location for the live Web site.

Anywhere that you see the word "expression" in any action options, you can use an interpreted ActionScript expression to specify the value of the option.

To use a string inside an expression, simply add quotation marks around it. Anything surrounded by quotation marks is taken as a literal string. For example, the conditional if (status == ready) wrongly checks whether the value of the variable status is the same as the value of the nonexistent variable ready. The correct conditional would check whether the value of status is the same as the string "ready" by quoting it, as in if (status == "ready").

You can even have expressions that indirectly refer to previously established variables. In ActionScript, you can use the dot syntax (and array access operators) to indirectly refer to variables, or you can use Flash 4's eval() function (to maintain backward compatibility).

We like to use the phrase "setting and getting" to help beginners understand how equations and expressions work in ActionScript code. An equation is any line of code that sets an object or variable to a new value. The order of syntax terms can be confusing to designers and developers new to code writing. Do you specify a value first? How do you know where to insert the equal sign (=)? If you remember the phrase "setting and getting," you'll know how to write basic equations. The variable you want to set (or assign a new value) is always on the left side of the equation, while the new value is always on the right:

 what you want to set = the value you want to get 

For example, if you wanted to set a variable named currentTime to the amount of time that has elapsed since the Flash movie started playing in the Flash Player, you would place currentTime on the left side of the equation and place the actual value of the time on the right side:

 current time in the movie = the number of milliseconds that have elapsed 

Translated into actual code, this would be:

 var currentTime = getTimer(); 

Again, another important aspect of variables to remember is that the name of a variable is quite arbitrary. What we called currentTime could just as well be named myTime, movieTime, elapsedTime — or whatever you want to call it. As long as you consistently refer to your variable's name in subsequent ActionScript code, everything will work as expected.

Array Access Operators

If you have a variable called name_1 declared on the Main Timeline, you can write the expression _root["name_" + "1"] to refer to the value of name_1. How is this useful? If you have more than one variable, but their prefixes are the same (for example, name_1, name_2, name_3, and so on), you can write an expression with two variables as a generic statement to refer to any one of the previously established variables: _root["name" + i], where i can be any predefined number. This type of expression is most commonly found in a code loop; you learn more about loops later in this chapter.

eval() Function and Flash 4's Set Variable

If you want to use old-fashioned ActionScript to indirectly refer to variable names and values, you have two ways to go about it:

  • Use the Set Variable action, specifying the variable name as a Slash-notated expression:

     set("/name_" add i, "Robert Reinhardt"); 

  • Use the eval() function, specifying the variable as an expression:

     eval("_root.name_" add i) = "Robert Reinhardt"; 

Note 

This usage is specific to Flash Player 4 and FlashLite 1.0/1.1 compatibility. Unless you are authoring movies to be compatible for these players, you should use the most current syntax.

Variables as Declarations

In most scripting languages, you usually don't have to declare a variable without its value; that is, you don't need to say variable firstName and then address it again with a value. In Flash ActionScript, you don't need to pre-establish a variable in order to invoke it.

Note 

As you start to code more complex scripts in ActionScript 2.0, such as creating custom classes, you do need to pre-declare variable names. As you're starting out with more basic scripts, you do not need to be so thorough with your code.

If you want to create a variable on the fly from a Movie Clip to the Main Timeline, you can. Most variables that you use in Flash will be declared in a timeline's keyframes. We'll show you how to create a couple of simple variables in a Flash document:

  1. Open a new Flash document (File ð New). In the New Document dialog box, choose Flash Document and click OK.

  2. Rename Layer 1 to actions.

  3. Select frame 1 of the actions layer in the Timeline window, and open the Actions panel by pressing the F9 key. Type the following action in the Script pane (see Figure 24-3):

     var firstName = "Franklin"; 

  4. Save your Flash document as variable_frame.fla, and test it (Ctrl+Enter or z+Enter). Choose Debug ð List Variables (Ctrl+Alt+V or Option+z+V). In the Output panel, you will see the following line of text:

     Variable _level0.firstName = "Franklin" 

image from book
Figure 24-3: A variable declaration in the Actions panel

Tip 

By default, the Output panel is grouped with the Property inspector, and you may find it awk- ward to look for ActionScript messages in this small area. You can undock the Output panel into its own window by clicking the options menu of the Property inspector (with the Output panel tab selected) and choosing Group Output with ð New panel group.

As you can see in this example, the firstName variable is shown at _level0, which is the _root of the current Flash movie. All variables belong to a specific timeline or object.

On the CD-ROM 

You can find the sample file, variable_frame.fla, in the ch24 folder of this book's CD-ROM.

Variables as Text Fields

Since Flash 4, text can be specified as text fields. A text field can be used as a dynamic text container whose content can be updated via ActionScript and/or the intervention of a server- side script (known in Flash 8 as Dynamic text), or it can accept input from the user (known in Flash 8 as Input text).

You can access a text field's properties by selecting the text field and opening the Property inspector. In the inspector, you can define the parameters of the text object, including its Var (for Variable) name and instance name.

Note 

Text fields in Flash 8 are TextField objects. The instance name of a TextField object should be different from the Var name. In fact, we recommend that, as a general rule of thumb, you do not specify a Var name for text fields in Flash Player 6 or higher movies.

An Input text field is editable when the Flash movie is played in the Flash Player; the user can type text into the text field. This newly typed text becomes the value of the text field's Var name, or the text property of the text field. On a login screen, you can create an Input text field with an instance name tLogin, where the user enters his or her name, such as Joe. In ActionScript, this would be received as tLogin.text = "Joe". Any text that you type into a text field during the authoring process will be that property's initial value.

To review this process of text fields and variable names, let's create a simple example:

  1. Create a new Flash document (File ð New). In the New Document dialog box, choose Flash Document and click OK.

  2. Rename Layer 1 to textfield.

  3. In the Tools panel, choose the Text tool, and click once on the Stage. Extend the text field to accommodate at least five characters. In the Property inspector (Window ð Properties), choose Input Text in the drop-down menu located at the top-left corner of the inspector. Click the Show border button in the inspector. In the <Instance Name> field, assign the instance name tFirstName. In the Var field, assign the name firstName_var. Refer to Figure 24-4.

  4. Save your Flash document as variable_textfield.fla, and test it (Ctrl+Enter or z+Enter). In the Test Movie window, type your name into the tFirstName text field. Then, choose Debug ð List Variables. Among other information, you will see the following lines of text:

     Variable _level0.firstName_var = "Holly" Edit Text: Target="_level0.tFirstName"     text = "Holly",     variable = "firstName_var", 

    Note that this sample assumes that the name Holly was typed into the text field.

image from book
Figure 24-4: The Property inspector settings for the Input Text field

This simple exercise demonstrates how the Var assignment of a TextField object differs from the instance name assignment. The actual text displayed in the TextField object can be accessed in two ways: as a variable called firstName_var, or as a property of the TextField object, tFirstName.text. Dynamic text fields behave in the same manner as well.




Macromedia Flash 8 Bible
Macromedia Flash8 Bible
ISBN: 0471746762
EAN: 2147483647
Year: 2006
Pages: 395

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