What are Data Types?


Simply put, ActionScript has several types of data that can be declared (or loaded) into the Flash movie. So far, you have worked primarily with three types of data in previous chapters: strings, numbers, and MovieClip objects. In this section, we define more data types available in ActionScript.

Understanding data types is rather straightforward. The most difficult aspect of working with data types is knowing which data types work correctly with the operation you want to perform in ActionScript. We will show you examples throughout this chapter to help you understand how data types are used.

String

You've seen String data types throughout this book already. Anytime you have a value in quotes, it is typed as a String. If you have an expression that refers to String data types, then its data type will be a string as well. All of the following examples have a String data type:

 var firstName = "Frank"; var lastName = "Houston"; var fullName = firstName + lastName; var pathSuffix = "1"; 

Tip 

All text contained with Input and Dynamic text fields have a data type of String. If you need to perform numeric operations with text field values, make sure you convert the string data to number data by using the Number() or parseInt() function. We discuss the number data type in the next section.

Note 

Feel free to try out the following code examples in new Flash document files. Create a new file, and rename Layer 1 to actions. Using the Actions panel, add the code examples to frame 1 of the actions layer. After you type each code block, test the movie to see the output from the trace() actions appear in the Output panel.

If a variable has a String data type, then any of the String object methods can be used with that data. For example, if you want to convert the case of all characters in the value of firstName to uppercase (turn "Frank" into "FRANK"), you could do the following operation:

 var firstName = "Frank"; var firstName = firstName.toUpperCase(); trace("firstName = " + firstName); 

Here, the String object method toUpperCase() converts any lowercase characters in a string value to uppercase characters. Likewise, you can extract specific information from a string. For example, if you wanted to find where a space occurs within a string, and return the value of the string from the point in the value to the end of the value, you could use the following code:

 var myVersion = "Netscape 7.2"; var startChar = myVersion.indexOf("") + 1; myVersion = myVersion.substr(startChar); trace("myVersion = " + myVersion); 

In the preceding code, the indexOf() method searches for the first occurrence of a space ("") within the string value for myVersion. indexOf("") for myVersion will return the position (as a number, counting from left to right) of the space character. For this example, indexOf("") will return 8. Then, 1 is added to this value to determine the character position after the space. In this example, the tenth position of myVersion's value is a "7". Then, by using the slice() method, you can extract the rest of the string from the startChar value of 9. Note that in this example, the final value of myVersion is a string value of "7.2".

Number

A Number data type is any value (or expression value) that refers to a discrete numeric value in ActionScript. A value must be typed as a number in order for it to work properly in mathematical operations.

 var myAge = "31"; var futureYears = "5"; myAge = myAge + futureYears; trace("I will be " + myAge + "years old in " + futureYears + "years."); 

If this code was added to frame 1 of your Flash document and tested, the following trace() information would appear in the Output panel:

 I will be 315 years old in 5 years. 

Obviously, this isn't the answer you were looking for. Because myAge and futureYears were specified as string values (with quotes), ActionScript simply concatenated (joined) the two string values as "31" + "5", which is "315". To see these values as numbers, you need to change the code to the following:

 var myAge = 31; var futureYears = 5; myAge = myAge + futureYears; trace("I will be " + myAge + "years old in " + futureYears + "years."); 

Now, the values of myAge and futureYears appear as real numbers to ActionScript, and the mathematical operation will add the values of myAge and futureYears correctly. The trace() output will now read:

 I will be 36 years old in 5 years. 

You can convert string data values to number data values by using the Number() function. In the string example from the last section, you could convert the myVersion string value to a number value by adding this line of code:

 myVersion = Number(myVersion); 

So, you can now perform mathematical operations on the "7.2" value of myVersion, which is now simply 7.2.

Note 

The process of converting one data type to another is sometimes referred to as casting.

Boolean

There will be times when you will designate a variable's value as either true or false. Variables that use true or false are said to have a Boolean value. Boolean values are useful for either/or situations, or when you need a toggle switch — just like a light switch, which is on or off. In the code that follows, a variable named isLoading is initialized with a true value, but later switched to a false value when loading is complete:

 onClipEvent(load){     var isLoading = true;     trace("isLoading's type = " + typeof(isLoading)); } onClipEvent(enterFrame){     if(this._framesloaded >= this._totalframes){         isLoading = false;     } } 

This code could be placed on a Movie Clip instance. When the Movie Clip instance appears on the Stage, the load event occurs, and the Output panel displays the following:

 isLoading's type = boolean 

You can check the data types of declared variables and objects with the typeof operator.

MovieClip

As the data type name implies, Movie Clip instances on the Stage have a data type of MovieClip. ActionScript distinguishes MovieClip objects from other code-based objects so that you can more easily detect MovieClip objects in your code. The following variable value will be typed as movieclip:

 var mc = this.ballAnim; 

As long as a Movie Clip instance named ballAnim exists on the current timeline (this), then mc's data type will be movieclip. If ballAnim did not exist, then mc's data type would be undefined. Because mc is classified as a movieclip, methods of the MovieClip class can then be applied to it. In the following code, the gotoAndStop(1) method will be passed along to ballAnim:

 mc.gotoAndStop(1); 

Object

This data type refers to most code-based objects you create with ActionScript. The following variables would be typed as Object:

 var myObject = new Object(); 

If you used this code in your Flash movie, you would see object types in the Output panel when Debug ð List Variables is used in the Test Movie environment:

 Variable _level0.myObject = [object #1, class ‘Object'] {} 

Several ActionScript classes will return a data type of object if tested with the typeof operator. We discuss the typeof operator later in this chapter.

Function

In ActionScript, you can define your own subroutines of ActionScript code. We discuss subroutines and constructor functions later in this chapter. The function data type will be assigned to any ActionScript code that begins with the function action, such as:

 function myGoto(label){ gotoAndStop(label); } 

You can also use the following syntax:

 var myGoto = function(label){      gotoAndStop(label); }; 

Caution 

There is a difference between declaring a function with the first technique versus the second technique. If you declare a function with the former method, then you can place the function anywhere within your code block, on any layer for a given frame — the function will be available to any other actions declared on that frame. If you use the latter method, the function will be available only to actions that occur below the function declaration and/or layers beneath the layer on which it was declared.

Undefined

If you check for the data type of a nonexistent code element, ActionScript will return a data type of undefined. For example, if you tried to create a variable that stored a reference to a MovieClip object that was not currently present on the Stage, a data type of undefined would be returned. Create a new Flash document with no elements on the Stage, in any frame. With the first frame of the document selected, type the following code into the Script pane of the Actions panel:

 var myMovieClip = mcBallAnim; trace("the data type of myMovieClip is " + typeof(myMovieClip)); 

Test your Flash movie (Ctrl+Enter or z+Enter). The Output panel will report:

 the data type of myMovieClip is undefined 

image from book
Strict Typing in ActionScript 2.0

In ActionScript 2.0, introduced with Flash MX 2004, you can declare variables with a strict data type. The format for such declarations is:

 var variableName:datatype; 

or

 var variableName:datatype = value; 

For example, if you type the following code into the Actions panel, you will declare a strictly typed string variable:

 var myName:String = "Robert"; 

In this example, the variable myName can only use values that have a data type of String. If a different data type is assigned to the variable, the ActionScript compiler will report an error when you publish or test your Flash movie. Try the following code in a new Flash document, on the first frame:

 var myName:String; myName = 7.2; 

Once you have entered this code, choose Control ð Test Movie. The Output panel will report the following error:

 **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 2: Type mismatch in assignment statement: found Number where String is required. myName = 7.2; 

Interesting, eh? That's a pretty specific error message, letting you know that you declared a number where a string value was expected. If you change the second line of code to

 myName = "Robert"; 

and retest the movie, you will no longer see the error message in the Output panel. So, why is strict typing important, after all is said and done? For the most part, strict typing forces you to carefully plan and map out the goals of your Flash movie, and discourages you from "free-form" coding, or coding haphazardly. By using strict typing with your ActionScript code, you can more easily debug problems in your Flash movies. Throughout this book and for the remainder of this chapter, we'll put strict typing to use. For the most comprehensive coverage of ActionScript 2.0, refer to the Flash 8 ActionScript Bible by Joey Lott and Robert Reinhardt (Wiley, 2006).

image from book

Checking Data Types with Typeof

Now that you know the various data types in ActionScript, you'll want to know how to check the data type of a given piece of information. Using the typeof operator, you can determine the data type of an ActionScript element. The typeof operator accepts only one option: the name of the ActionScript element that you wish to test. For example, you can trace a variable (or object) type in the Output panel:

 var firstName:String = "Robert"; trace("firstName has a data type of " + typeof(firstName)); 

When this movie is tested, the Output panel will display:

 firstName has a data type of string 

You can use typeof in for ... in loops, so that actions will be executed with specific data types. The following ActionScript code will take any string variables on the Main Timeline and move them to the _global namespace:

 for(name in _root){   if(typeof(_root[name])==" string" && _root[name] != _root["$version"]){      _global[name] = _root[name];      delete _root[name];  } } 

This code block will move all variables except the native $version variable to the new _ global namespace.

On the CD-ROM 

You can see the returned values of the typeof operator in the typeof_simple_AS1.fla, typeof_simple_AS2.fla, typeof_advanced_AS1.fla, typeof_advanced_AS2.fla, and moveVariables.fla files, located in the ch26 folder of this book's CD-ROM.

Checking Class Type with Instanceof

Flash Player 6 introduced the instanceof operator to ActionScript. With this operator, you can check the class type of a specific object in ActionScript. A class is similar to a data type, but a little more detailed. As we mentioned in the Object data type discussion, some different objects returned object as their data type. However, these objects belong to different classes. In fact, you probably noticed the class type showing up in the Output window when you chose Debug ð List Variables.

We'll show you an example that compares typeof to instanceof. Create a new Flash document, and select frame 1 of the default layer. In the Actions panel, type the following code into the Script pane:

 var dCurrent:Date = new Date(); trace("the data type of dCurrent is " + typeof(dCurrent)); 

After you've written this code, test the Flash movie (Ctrl+Enter or z+Enter). The Output panel will display the following text:

 the data type of dCurrent is object 

Now, use the typeof operator in an if statement. After the last line of code that you typed, enter the following code:

 if(typeof(dCurrent) == "object"){   trace("dCurrent has a data type of object"); } 

When you save and test this movie, the last line of the Output panel will be:

 dCurrent has a data type of object 

However, if you wanted to check what kind of object dCurrent was, the typeof operator would not be able to help you out. Enter the instanceof operator. Add the following code to the actions list for frame 1:

 if(dCurrent instanceof Date){   trace("currentDate is a Date object"); } 

When you test the movie, you will see the following text display in the Output panel:

 dCurrent is a Date object 

Now, try an if/else statement that compares currentDate to a different class, such as Sound. Add the following code into the Actions panel for frame 1:

 if(dCurrent instanceof Sound){   trace("dCurrent is a Sound object"); } else {   trace("dCurrent is not a Sound object"); } 

When you test your movie, you will see the following text displayed in the Output panel:

 dCurrent is not a Sound object 

While these are simple tests, you can start to see how instanceof allows you to check the class types of your data.

Note 

When you use the instanceof operator, you do not wrap the compared value in quotes, as you do with typeof. For example, do not use if(dCurrent instanceof "Date"). Simply refer to the class by name, without the quotes: if(dCurrent instanceof Date).




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