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

Chapter 4. Data and Data Types > About data types

About data types

A data type describes a piece of data and the kinds of operations that you can perform on it. You store data in a variable. You use data types when creating variables, object instances, and function definitions to assign the type of data you’re working with. You use many different data types when you write ActionScript.

ActionScript 2.0 defines several commonly used data types. Data types describe the kind of value that a variable or ActionScript element can contain. A variable that is assigned a data type can only hold a value within that data type’s set of values. For information on variables, see “About variables” on page 89.

ActionScript has numerous basic data types that you will probably use frequently in your applications. See the table in “About primitive and complex data types” on page 75 for more information.

ActionScript also has core classes, such as Array and Date, that are considered complex or reference data types. For more info on complex and reference data types, see “About primitive and complex data types” on page 75. In addition, all data types and classes are fully defined in ActionScript 2.0 Language Reference in Flash Help.

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” on page 292. For more information on creating custom classes, see Chapter 7, “Classes,” on page 231.

In ActionScript 2.0, you can assign data types to variables when you declare them. The data types you assign can be any of the core types or can represent a custom class that you created. For more information, see “About assigning data types and strict data typing” on page 83.

When you debug scripts, you might need to determine the data type of an expression or variable to understand why it is behaving a certain way. You can do this with the instanceof and typeof operators (see “About determining data type” on page 88).

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\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DataTypes.

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

About primitive and complex data types

You can divide all the different data type values into two main categories: primitive or complex.

A primitive value (or primitive data type) is a value that ActionScript stores at the lowest level of abstraction, which means that operations on the primitive data types are generally faster and more efficient than operations carried out on complex data types. The following data types all define a set of one or more primitive values: Boolean, null, Number, String, and undefined.

A complex value (or complex data type) is a value that is not a primitive value and that references the primitive values. Often, these are called reference data types. Complex values belong to the Object data type or a data type that is based on the Object data type. Data types that define sets of complex values include Array, Date, Error, Function, and XML. For more information on these complex data types, see their entries in the ActionScript 2.0 Language Reference in Flash Help.

Variables that contain primitive data types behave differently in certain situations than those containing complex types. For more information, see “Using variables in a project” on page 108.

ActionScript has the following basic data types that you can use in your applications:

Data typeDescription
BooleanPrimitive. 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. For more information, see “Boolean data type” on page 77.
MovieClipComplex. The MovieClip data type lets you control movie clip symbols using the methods of the MovieClip class. For more information, see “MovieClip data type” on page 78.
nullPrimitive. The null data type contains the value null. This value means no value–that is, a lack of data. You can assign the null value in a variety of situations to indicate that a property or variable does not have a value assigned to it. The null data type is the default data type for all classes that define complex data types. An exception to this rule is the Object class, which defaults to undefined. For more information, see “null data type” on page 80.
NumberPrimitive. This data type can represent integers, unsigned integers, and floating point numbers. To store a floating point number, you should include a decimal point in the number. Without the decimal point, the number is stored as an integer. The Number data type can store values from Number.MAX_VALUE (very high) to Number.MIN_VALUE (very low). For more information, see ActionScript 2.0 Language Reference in Flash Help and “Number data type” on page 80.
ObjectComplex. The Object data type is defined by the Object class. The Object class serves as the base class for all class definitions in ActionScript, and it lets you arrange objects inside each other (nested objects). For more information, see “Object data type” on page 81.
StringPrimitive. The String data type represents a sequence of 16-bit characters that might include letters, numbers, and punctuation marks. Strings are stored as Unicode characters, using the UTF-16 format. An operation on a String value returns a new instance of the string. For more information, see “String data type” on page 82.
undefinedPrimitive. The undefined data type contains one value: undefined. This is the default value for instances of the Object class. You can only assign a value of undefined to variables that belong to the Object class. For more information, see “undefined data type” on page 83.
VoidComplex. The Void data type contains only one value: void. You use this data type to designate functions that don’t return a value. Void is a complex data type that references the primitive Void data type. For more information, see “Void data type” on page 83.


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\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DataTypes.

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

Boolean data type

A Boolean value is one that is either true or false. ActionScript also converts the values true and false to 1 and 0 when appropriate. Boolean values are most often used with logical operators in ActionScript statements that make comparisons to control the flow of a script.

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

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

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

// Add two TextInput components, a Label, and a Button component on the
  Stage.
// Strict data type the three component instances
var userName_ti:mx.controls.TextInput;
var password_ti:mx.controls.TextInput;
var submit_button:mx.controls.Button;
var welcome_lbl:mx.controls.Label;

//Hide the label
welcome_lbl.visible = false;

// Create a listener object, which is used with the Button component.
// When the Button is clicked, checks for a user name and password.
var btnListener:Object = new Object();
btnListener.click = function(evt:Object) {
  // Checks that the user enters at least one character in the TextInput
  // instances and returns a Boolean true/false.
  var userNameEntered:Boolean = (userName_ti.text.length > 0);
  var isPasswordCorrect:Boolean = (password_ti.text == "vertigo");
  if (userNameEntered && isPasswordCorrect) {
    var titleMessage:String = "Welcome " + userName_ti.text + "!";
    welcome_lbl.text = titleMessage;
    //display the label
    welcome_lbl.visible = true;
  }
};
submit_button.addEventListener("click", btnListener);


					  

For more information, see “Using functions in Flash” on page 219 and “About logical operators” on page 198.

MovieClip data type

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

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

Working with movie clips on the Stage The following example calls the startDrag() and getURL() methods for different movie clip instances that are on the Stage:

my_mc.startDrag(true);
parent_mc.getURL("http://www.macromedia.com/support/" + product);

The second example returns the width of a movie clip called my_mc on the Stage. The targeted instance must be a movie clip, and the returned value must be a numeric value.

function getMCWidth(target_mc:MovieClip):Number {
  return target_mc._width;
}
trace(getMCWidth(my_mc));

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

To dynamically create a movie clip, use MovieClip.createEmptyMovieClip(), as shown in the following example:

// Creates a movie clip to hold the container.
this.createEmptyMovieClip("image_mc", 9);
// Loads an image into image_mc.
image_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");

The second example creates a movie clip called square_mc that uses the Drawing API to draw a rectangle. Event handlers and the startDrag() and stopDrag() methods of the MovieClip class are added to make the rectangle draggable.

this.createEmptyMovieClip("square_mc", 1);
square_mc.lineStyle(1, 0x000000, 100);
square_mc.beginFill(0xFF0000, 100);
square_mc.moveTo(100, 100);
square_mc.lineTo(200, 100);
square_mc.lineTo(200, 200);
square_mc.lineTo(100, 200);
square_mc.lineTo(100, 100);
square_mc.endFill();
square_mc.onPress = function() {
  this.startDrag();
};
square_mc.onRelease = function() {
  this.stopDrag();
};

For more information, see Chapter 11, “Working with Movie Clips,” on page 357 and the %{MovieClip}% entry in the ActionScript 2.0 Language Reference in Flash Help.

null data type

The null data type has only one value, null. This value means no value—that is, a lack of data. You can assign the null value in a variety of situations to indicate that a property or variable does not yet have a value assigned to it. For example, you can assign the null value in the following situations:

  • To indicate that a variable exists but has not yet received a value

  • To indicate that a variable exists but no longer contains a value

  • As the return value of a function, to indicate that no value was available to be returned by the function

  • As a parameter to a function, to indicate that a parameter is being omitted

Several methods and functions return null if no value has been set. The following example demonstrates how you can use null to test if form fields currently have form focus:

if (Selection.getFocus() == null) {
  trace("no selection");
}

Number data type

The Number data type is a double-precision floating-point number. The minimum value of a number object is approximately 5e-324. The maximum is approximately 1.79E+308.

You can manipulate numbers using the arithmetic operators addition (+), subtraction (-), multiplication (*), division (/), modulo (%), increment (++), and decrement (--). For more information, see “Using numeric operators” on page 192.

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

The following example uses the sqrt() (square root) method of the Math class to return the square root of the number 100:

Math.sqrt(100);

The following example traces a random integer between 10 and 17 (inclusive):

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

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

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

Object data type

An object is a collection of properties. A property is an attribute that describes the object. For example, the transparency of an object (such as a movie clip) is an attribute that describes its appearance. Therefore, _alpha (transparency) is a property. Each property has a name and a value. The value of a property can be any Flash data type—even the Object data type. This lets you arrange objects inside each other, or nest them.

To specify objects and their properties, you use the dot (.) operator. For example, in the following code, hoursWorked is a property of weeklyStats, which is a property of employee:

employee.weeklyStats.hoursWorked

The ActionScript MovieClip object has methods that let you control movie clip symbol instances on the Stage. This example uses the play() and nextFrame() methods:

mcInstanceName.play();
mc2InstanceName.nextFrame();

You can also create custom objects to organize information in your Flash application. To add interactivity to an application with ActionScript, you need many pieces of information: for example, you might need a user’s name, age, and phone number; the speed of a ball; the names of items in a shopping cart; the number of frames loaded; or the key that the user pressed last. Creating custom objects lets you organize this information into groups, simplify your scripting, and reuse your scripts.

The following ActionScript code shows an example of using custom objects to organize information. It creates a new object called user and creates three properties, name, age, and phone, which are String and Numeric data types.

var user:Object = new Object();
user.name = "Irving";
user.age = 32;
user.phone = "555-1234";

For more information, see “Example: Writing custom classes” on page 269.

String data type

A string is a sequence of characters such as letters, numbers, and punctuation marks. You enter strings in an ActionScript statement by enclosing them in single (') or double (") quotation marks.

A common way that you use the string type is to assign a string to a variable. For example, in the following statement, "L7" is a string assigned to the variable favoriteBand_str:

var favoriteBand_str:String = "L7";

You can use the addition (+) operator to concatenate, or join, two strings. ActionScript treats spaces at the beginning or end of a string as a literal part of the string. The following expression includes a space after the comma:

var greeting_str:String = "Welcome, " + firstName;

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

Escape sequenceCharacter
\bBackspace character (ASCII 8)
\fForm-feed character (ASCII 12)
\nLine-feed character (ASCII 10)
\rCarriage return character (ASCII 13)
\tTab character (ASCII 9)
\"Double quotation mark
\'Single quotation mark
\\Backslash
\000 - \377A byte specified in octal
\x00 - \xFFA byte specified in hexadecimal
\u0000 - \uFFFFA 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.

The String class is a built-in ActionScript class. For information on the methods and properties of the String class, see the %{String}% entry in the ActionScript 2.0 Language Reference in Flash Help.

undefined data type

The undefined data type has one value, undefined, and is automatically assigned to a variable to which a value hasn’t been assigned, either by your code or user interaction.

The value undefined is automatically assigned; unlike null, you don’t assign undefined to a variable or property. You use the undefined data type to check if a variable is set or defined. This data type lets you write code that executes only when the application is running, as shown in the following example:

if (init == undefined) {
  trace("initializing app");
  init = true;
}

If your application has multiple frames, the code does not execute a second time because the init variable is no longer undefined.

Void data type

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

//Creates a function with a return type Void
function displayFromURL(url:String):Void {}

About assigning data types and strict data typing

You use variables in Flash to hold values in your code. You can explicitly declare the object type of a variable when you create the variable, which is called strict data typing.

If you do not explicitly define an item as holding either a number, a string, or another data type, at runtime Flash Player will try to determine the data type of an item when it is assigned. If you assign a value to a variable, as shown in the following example, Flash Player evaluates at runtime the element on the right side of the operator and determines that it is of the Number data type:

var x = 3;

Because x was not declared using strict data typing, the compiler cannot determine the type; to the compiler, the variable x can have a value of any type. (See “Assigning a data type” on page 84.) 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.

For more information on creating variables, see “About variables” on page 89. For information on naming variables, see “About naming variables” on page 94. For more information on assigning data types, and the types you can assign, see “Assigning a data type” on page 84.

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\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DataTypes.

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

Assigning a data type

You need to assign data types whenever you define a variable, whether you declare a variable using the var keyword, create a function argument, set function return type, or define a variable to use within a for or for..in loop. To assign a data type, you use post-colon syntax, which means you follow the variable name with a colon and then the data type:

var my_mc:MovieClip;

There are many possibilities for data types, ranging from the native data types such as Number, String, Boolean, or built-in classes that are included in Flash Player 8, such as BitmapData, FileReference, or even custom classes that you or other developers have written. The most common types of data types you might need to specify are the built-in data types such as Number, String, Boolean, Array, or Object, which are shown in the following code examples.

To assign a specific data type to an item, specify its type using the var keyword and 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. For more information, see “About assigning data types and strict data typing” on page 83.

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.

For information on type checking, see “About type checking” on page 87.

About type checking

Type checking refers to verifying that the type of a variable and an expression are compatible. Therefore, Flash checks that the type you specify for a variable matches the value(s) that you assign to it. For more information on strict data types and assigning data types, see “About assigning data types and strict data typing” on page 83 and “Assigning a data type” on page 84.

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

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

For more information about these operators, see %{typeof operator}% and %{instanceof operator}% in the ActionScript 2.0 Language Reference in Flash Help. For more information on testing and debugging, see Chapter 18, “Debugging Applications,” on page 725 For more information on inheritance and interfaces, see Chapter 8, “Inheritance,” on page 307. For more information on classes, see Chapter 7, “Classes,” on page 231.

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