You are on page 1of 56

Lecture 12 Data and Data Types

Data refers to the numbers, strings,

and other information that you can manipulate within Flash. Using data is usually essential when you create applications or websites. You also use data when you create advanced graphics and script-generated animation, and you might have to manipulate values that you use to drive your effects.

You can define data in variables within Flash, or you can load data from external files or sites using XML, web services, built-in ActionScript classes, and so on. You can store data in a database, and then represent that information in several ways in a SWF file. This can include displaying the information in text fields or components, or displaying images in movie clip instances.

Some of the most common kinds of data include strings (a sequence of characters, such as names and passages of text), numbers, objects (such as movie clips), Boolean values (true and false), and so on.

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 youre working with. You use many different data types when you write ActionScript.

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 types set of values. ActionScript has numerous basic data types that you will probably use frequently in your applications.

ActionScript also has core classes, such as Array and Date, that are considered complex or reference data types. You can also create custom classes for your applications. Any class that you define using the class declaration is also considered a data type. In ActionScript 2.0, you can assign data types to variables when you declare them. The data types you assign can be any of the core types or can represent a custom class that you created.

When you debug scripts, you might need to determine the data type of an expression or variable to understand why it is behaving a certain way. You can convert one data type to another at runtime using one of the following conversion functions: Array(), Boolean(), Number(), Object(), String().

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.

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

Primitive. The Boolean data type consists of two values: true and false. No other values are valid for variables of this type. The default value of Boolean variable that has been declared but not initialized is false.

Complex. The MovieClip data type lets you control movie clip symbols using the methods of the MovieClip class.

Primitive. The null data type contains the value null. This value means no valuethat 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.

Primitive. This data type can represent integers, unsigned integers, and floating point numbers. To store a floating point number, you should include a decimal point in the number. Without the decimal point, the number is stored as an integer. The Number data type can store values from Number.MAX_VALUE (very high) to Number.MIN_VALUE (very low).

Complex. The Object data type is defined by the Object class. The Object class serves as the base class for all class definitions in ActionScript, and it lets you arrange objects inside each other (nested objects).

Primitive. The String data type represents a sequence of 16-bit characters that might include letters, numbers, and punctuation marks. Strings are stored as Unicode characters, using the UTF-16 format. An operation on a String value returns a new instance of the string.

Primitive. The undefined data type contains one value: undefined. This is the default value for instances of the Object class. You can only assign a value of undefined to variables that belong to the Object class.

Complex. The Void data type contains only one value: void. You use this data type to designate functions that dont return a value. Void is a complex data type that references the primitive Void 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.

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/su pport/" + 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.

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.helpexamp les.com/flash/images/image1.jpg");

The null data type has only one value, null. This value means no valuethat 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.

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

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

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

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

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:

The undefined data type has one value, undefined, and is automatically assigned to a variable to which a value hasnt been assigned, either by your code or user interaction. The value undefined is automatically assigned; unlike null, you dont 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; }

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

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 82.) A later assignment might change the type of x; for example, the statement x = "hello" changes the type of x to String.

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;

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

You might also like