Вы находитесь на странице: 1из 148

Introduction to ActionScript 3

ActionScript 3.0 is the internal programming language for Flash, Flex, and AIR (the Adobe Integrated Runtime application). With AS3 (ActionScript 3.0) you can write instructions to control the elements in a Flash presentation. For example, you can add instructions for buttons to play and stop an animation, or to change the color and size of an object. Also, ActionScript can be used to add objects (shapes, lines, text) in a Flash presentation without creating them on the Stage. ActionScript is the programming language used to create Flash games which can be included in Web pages. ActionScript 3.0 was introduced by Adobe in 2006 with "Adobe Flex 2.0". It is a scripting language similar to JavaScript, for example, both languages uses the keyword "var" to declare the variables, the strings are joined with the "+" character. If you know JavaScript, you'll understand and learn faster AS3. ActionScript 3.0 requires an object-oriented approach, includes some of the new concepts of objectoriented programming (OOP): classes, objects, methods, and events.

To create a Flash presentation which uses ActionScript 3, open a new document choosing "ActionScript 3.0" from the "Create New" column in the Flash start window (or from File -> New). You can place the ActionScript code in frames in the Flash Timeline, or you can place your code in a completely separate ActionScript (.as) file. For a start it will be shown how to add the code directly into the document, in Frames in the Timeline. After you have opened a new document, create a new Layer in the Timeline (from Insert -> Timeline -> Layer) and call it actions or scripts (you can change the name of the Layer by double-clicking on its name). It's better to keep your ActionScript code in a single layer at the top of the timeline that holds only AS3 code. Also, you can use any name for this layer, but it's better to have a suggestive name. The ActionScript code will be write in a special panel (an Actions panel, shown in the picture below). To open the Actions panel, cick a keyframe where you want to add your code, then click Window -> Acions (or press F9).

Actions panel

- The Actions pannel is used to add code and AS3 instructions in the Flash document. - At the bottom of the picture is the Timeline panel, with the layer "Actions" created for adding ActionScript codes to its Frames. The code here is added in the first keyframe.

ActionScript type - choose the ActionScript version for the code write in Script pane Toolbox - holds a list of ActionScript objects, properties, methods, and events. Navigator pane - shows a list of Frames that have ActionScript code attached. Script tag - indicates which script is being edited. Pin Script - adds a tab for a selected script. Script pane - is where you type the ActionScript code. Help - provides online help. Script Assist - provides a visual interface for editing scripts (syntax completion and parameter descriptions). Options menu - contains options that control and format the Actions panel. Code Snippet - provides ActionScript 3.0 code segments to use in scripts.

Toolbar Actions - provides helpful tools for working with your ActionScript code (the buttons are shown in the image below).

o o o

o o o o o o

o o o o o

Add script items - provides access to the same elements as the Actions toolbox. Find - searches your script for words and characters. Insert a target path - inserts a specific target clip into the action. - Click this button, and then choose your target object from a list, and this tool writes the proper code identifying it. Check syntax - checks the current action for syntax errors. Autoformat - formats your script, making it easier to read, by using colors and indents. - To set formatting options, go to Edit -> Preferences -> ActionScript. Show code hint - gives you hints to the syntax of the action as you type. Debug options - add or remove breakpoints into the action to pause on the specified line of code, giving you an opportunity to examine your program. Expand all - expands collapsed portions of your script after you've used "Collapse selection" or "Collapse between braces". Collapse selection - collapses selection. - Select the text you want to hide, and then click this button to hide it. If you hold down the Alt key when you click this button, the Actions panel collapses the code not selected. Collapse between braces - hides the text between a set of curly braces {}. Apply block comment - inserts the /* and */ used to create a block comment. Apply inline comment - inserts the // used to create an inline comment. Remove comment - removes the comment characters from a comment. Show/Hide toolbox - creates more room for the Script pane, hiding the Actions toolbox. - When the toolbox is hidden, you can use the "Add script items" button to insert elements.

AS3 is case-sensitive, so: "you", "You" and "YOU" are three different things.

A simple script ActionScript 3


Before proceeding with the presentation of the ActionScript 3 language elements, here is a simple script to see from the beginning how easily you can create objects (text, shapes) into a Flash presentation using ActionScript code. - Follow these steps: 1. Open a new Flash document (ActionScript 3.0). 2. Right-click on the first Frame in the Timeline, and then choose Actions. 3. In the "Actions panel" (the window used to write ActionScript code) add the following code:
var site:TextField = new TextField(); // declare the "site" variable ("TextField" type) site.text = "www.marplo.net"; // add a text in "site" variable addChild(site); // add the variable (its value) in Flash presentation

4. Press "Ctrl+Enter" to see the result - This ActionScript code will display the text "www.marplo.net" in the Flash presentation. You can create many other elements in a Flash presentation with ActionScript: lines, geometric shapes, animation, etc. In the next example we add a square to the presentation created above (see also the explanations in comments). 5. Continue the above example. In the same Actions panel add the code bellow, after the existing code, as shown in this image:

- If you have closed the Actions panel, right-click on Frame 1 and choose "Actions".

var square:Shape = new Shape; ("Shape" type) square.graphics.beginFill(0x08fe08); "beginFill(0xRRGGBB)

// declare the "square" variable // add a color to "square", with

// define the "square" (position and size, in pixels), with "graphics" property and "drawRect(X, Y, width, height)" method square.graphics.drawRect(0, 20, 100,100); addChild(square); // add the square in Flash presentation

6. Press "Ctrl+Enter" to see the rezult. Flash will display a window with a text and a green square like in the picture below.

The FLA file with this example can be downloaded from: Simple script AS3. So, step by step, with ActionScript you can create complex Flash presentations, the objects you add and their properties can be controlled with AS3 methods and properties. For example, to add transparency to the square in the example above, you can use the "beginFill(color, nr_alpha)" method (for "nr_alpha" add a number between 0 and 1), like this: square.graphics.beginFill(0x08fe08, 0.5);

Understanding OOP - Object Oriented Programming


Object-Oriented programming (OOP) is a specific programming technique to create chunks of programming code (called "objects") that do a specific job, and divide the script into distinct pieces that can be easily managed. These pieces of code can be grouped to form another object. - For example, the wheels, frame, the pedal, and the handlebars of a bike are separate objects, but if you unite them, they can form a bicycle, which also can be considered an object. The same is in ActionScript programming, the text, line, shape, movie clip symbol, functions, etc., anything is considered an object. Objects are defined using two primary identifiers (or members): properties and methods.

Properties - are characteristics that define an object. - For example, "color" can be property of a DVD player. Methods - are actions that can be performed by an object. For example, Play, and Pause are methods of a DVD player.

In programming, "method()" is a function defined in the code of a class, so it uses round brackets. - Becouse the method is basically a function, it can have one or more parameters (separated by comma) within brackets. method(parameter1, parameter2) The dot operator (.) is used to access the members of an objects (properties and methods). Each code line should end with a semicolon (;) E.g. object.property.method(); The characteristics of an object can be changed through its properties and methods. To assign or change the value of a property, use the following syntax:
object.property = value;

- Example:
// square is the object, width is the property, and 100 is the value square.width = 100;

There are methods that can be called to define a property of an object, with the syntax:
object.property.method();

- Example:
// the beginFill() method defines the graphics property of the object "square" square.graphics.beginFill(0x08fe08);

And methods that can be applied directly to the object:


object.method();

- Example:
// gotoAndStop(9) method moves the curent Frame in myClip animation to Frame 9, and stop

myClip.gotoAndStop(9);

In addition to objects, properties and methods, in OOP there are elements known as "events".

event - is the action of an application or user, such as a mouse click, that triggers an action related to an object.

So, the following elements are used in OOP (Object Oriented Programming):

classes - is a collection of related properties, methods, and events that are grouped in one colection. It contains the code which define the data type, state, and behaviors of an object. - A class is like a generalized blueprint for building an object. Instances - is a specific object that can uses the properties and methods of a class. Properties - characteristics that define an object. Methods - actions that an object can perform. Events - actions that can trigger the execution of a function, or instructions. Events can be the actions of the mouse cursor (mouse clicks or mouse movements.), the keybord actions (pressed keys). There are also Frame events (like the Flash playhead moving into or out of specific frames), Load events (which report on the progress when loading external files), and other event types.

To understand how these elements work, try the following example. - We create a Flash presentation that changes the size and position of a square when we click a button. Notice how the OOP elements are used: object, property, event, and how to make the connection between objects on the Stage and ActionScript code. 1. Open a new Flash document (ActionScript 3.0), select the "Rectangle tool" and draw a square on the stage. 2. Convert the square into Movie Clip symbol (from Modify -> Convert to Symbol, and select "Movie Clip" Type). - The square on the Stage becomes an instance of the Movie Clip symbol. Before you can control objects on the Flash stage with ActionScript, you have to convert them to movie clip or button symbols. 3. With the square selected, open the "Properties panel" and give this instance the name square - The name of an Instance on the Stage is added in the "Properties panel", in the field where you see: "<Instance Name>". This step is important. If you give objects on the stage a name, you can use their name in the script code to tell ActionScript exactly which object you're talking about. The name of an instance on the stage will represent that object in the script code. 4. Select the "Oval tool" and draw a circle near the square (as shown in the imge below), then convert this circle into Button symbol (from Modify -> Convert to Symbol, and select "Button" Type).

Make sure the circle on the stage is selected, and then in the "Properties panel" type buton in the "Instance Name" box, as shown in the picture below.

5. Create a new layer in the Timeline (from Insert -> Timeline -> Layer), double-click the layer name, and then type "actions". It's good programming practice to create a separate layer in the Timeline for your ActionScript code. Naming it "actions" or "scripts" makes it clear that the layer is reserved for code. 6. Right-click on Frame 1 in "actions" layer and choose Actions. 7. In the "Actions panel" add the following code:
// registers an event listener for "buton" object buton.addEventListener(MouseEvent.CLICK, setWidth); // defines the function accessed by the event function setWidth(evt) { // set the width and Y position for "square" instance square.width = 115; square.y = 100; }

8. Press "Ctrl+Enter" to see the result. The Flash Player will display a presentation like this (click on the yellow circle, which is the button): The FLA file with this example can be downloaded from: Understanding OOP. - "addEventListener()" is an ActionScript method used to "registers an event listener". The first parameter is the event the listener is listening ("MouseEvent.CLICK"). The second parameter is the name of the function ("setWidth") that run when the event happens. - "setWidth()" executes the code added within its curly brackets {} when it is accessed.

Variables, Comments and trace()


Variables
Variables are elements that store data. A good analogy for a variable is a box for carrying something around. It isn't the box itself that is important, it is whatever the box contains that is really important. So, important to a variable is the data it holds. Like there are many different types of box, depending on the thing they carry, the same there are many different types of variables. A variable can contains a number, a string (words), a boolean (true or false) value, a URL(web address), an array (list of values).

Variables must be declared before they can be used. The syntax to create (declare) a variable is:
var variable_name:DataType = value;

Or:
var variable_name:DataType; variable_name = value;

- "var" is a reserved keyword used to declare a variable. - "DataType" specifies the type of data that a variable contains. Although the DataType is not strictly required, it is considered best practice to specify the data type (will reduce the amount of memory that Flash will use to recognize the type of variable data). The "variable_name" can be any name that follow these rules:

Variables name cannot begin with a number. They cannot contain spaces. Don't use any reserved words, like "var", "Number" (the ones that turn blue).

- Example:
// declare a variable that would hold a numerical value, and set this value to 78 var num:Number = 78; // create a variable that would hold a string value, and then set a value var str:String; str = "coursesweb.net";

The name of the variable permits the access at its value and also can change the value if necessary. You can assign the value of a variable to another variable. - Example:
// declare numerical variable var num:Number = 78; // declare another numerical variable, and assign it the value of "num"

var num2:Number = num; // change the value of "num" variable num = 89;

The main data type used in ActionScript are:


Boolean - values of this type can only be true or false String - used for any text value or string characters (between quotes) Number - used for any numeric value, including decimal values int - only for integer values uint - only for positive integers Array - used to store a list of multiple values Date - for values that indicate a date and/or time RegExp - used for regular expressions URLRequest - for variables that store a web adress (URL) null - used for variables that do not have a value at all void - is used for function that do not return any value * - used if a variable is not of a specified type undefined - indicates untyped variable that have not been initialized

Important: - becouse ActionScript is case-sensitive, you must follow the exact syntax. For example, "string" is different from "String". Comments The comments within the code are necessary when we want to specify the role and functions of certain variables or instructions, for easy understanding of the script later. To add a comment on a single line, inside the code, use double slash //. All characters to the right of the double slash represent a comment. - Example:
// Comment on a single line var a_var:String = "some text";

If you want to write comments on multiple lines, use /* at the beginning of the comment, and */ at its end. - Example:
/* comment on ... multiple lineas another line ... */ var a_var:String = "some text";

The trace() function


The trace() function is a special kind of statement used to display information to the Output panel in Flash. The trace statement is a useful tool for debugging the code, to check the values that a variable or function returns. Like any function, you pass values to the trace() function by placing them inside the parentheses. - Syntax:
trace(parameter)

If you put a string inside the parentheses, like trace("Have a good life"), Flash shows that string in the Output panel when you test your presentation (with "Ctrl+Enter"), and the execution of your code reaches the trace() statement. If you put a variable inside the parentheses, like trace(var_name), Flash shows the value of that variable in the Output panel. - Here is an example with the elements presented in this tutorial (variables, comments and trace()): 1. Open a new Flash document (ActionScript 3.0) 2. Right-click on Frame 1 in the Timeline, and choose Actions 3. In the "Actions panel" add the folloing code:
/* Comments on multiple lines - ActionScript example: variables, comments and trace() - Web Site: http://coursesweb.net/ */ // declares two variables (String and Number type) var str:String = 'AS3 Tutorial'; var num:Number = 789; // using trace(); trace(str); trace('Current frame: '+ this.currentFrame); Frame number

// Checks the curent

- Notice that you can add comments to a line with executable code, but after the end of that instruction. The parameter of the second "trace()" statement is a slightly more complex expresion. The '+' operator can be used to join string variables or text values together. The "this.currentFrame" returns the current frame number. 4. Press "Ctrl+Enter". The Flash Player will display a blank window, important is the "Output panel" in Flash, which displays the results returned by the trace() function, as shown in the image below.

- The first trace() statement returns the value of the "str" variable ("AS3 Tutorial"), the second trace() outputs the value of the expression between brackets ("Current frame: 1").

Constants and Operators


Constants
Constants are a special kind of variable, store a value that never changes during the course of the program. The syntax to create a Constant is:
const CONSTANT_NAME:DataType = value;

- "const" is the special keyword, reserved to define a constant. As you can see, this syntax looks a lot like a variable declaration but with the var keyword replaced with "const". Most programmers use all caps for the name of the constants to differentiate them from variables. - Example (we define two constants and output their value):
const BROTHER:String = 'Victor'; const BROTHER_AGE:uint = 33; // output with "trace()" the value of these constants trace(BROTHER+ ' - '+ BROTHER_AGE); // in the Output panel will display: Victor - 33

If you try to change the value of a constant, you get an error messages.

Operators
Operators are special symbols used to take one, two or more operands (values, variables, expresions) and return a value. For example, the most known operators are: + (addition), and - (subtraction). The operators can be used to change, combine and evaluate data in a script. Operators can be divided into multiple groups:

Arithmetic operators

+ - addition o 2 + 3 , var1 + var2 - - subtraction o 2 - 3 , var1 - var2 * - multiplication o 2 * 3 , var1 * var2 / - division o 2 / 3 , var1 / var2 % - modulo (divides the first number by the second and returns the leftover portion only) o 8 % 3 (return 2) , var1 % var2

When there's more than one arithmetic operator, the execution follows the arithmetic rules (will first execute multiplication, division or modulo, and then addition and subtraction, if you use Parentheses, their code will be evaluated first before moving on to other operations). - Example:

var num:Number = 3 + 4 * 5; var num:Number = (3 + 4) * 5;

// result 23 // result 35

The "+" operator can also be used to join (concatenate) strings. - Example:
var str:String = 'ActionScript course '; var str2:String = str + 'coursesweb.net'; trace(str2); // ActionScript course coursesweb.net

Increment (++) and decrement ( )


Increment (++) and decrement ( ) operators are used to add or substract 1 from a number. They require only one argument:

var num:Number = 15; num++; // 16 num--; // 15

Compound arithmetic operators


The compound arithmetic operators provide a shorthand solution to performing arithmetic on numbers.

+=
o

var1 += nr; (equivalent to: var1 = var1 + nr; // "nr" can be a number or a variable) var1 -= nr; (equivalent to: var1 = var1 - nr; // "nr" can be a number or a variable) var1 *= nr; (equivalent to: var1 = var1 * nr; // "nr" can be a number or a variable) var1 /= nr; (equivalent to: var1 = var1 / nr; // "nr" can be a number or a variable) var1 %= nr; (equivalent to: var1 = var1 % nr; // "nr" can be a number or a variable)

-=
o

*=
o

/=
o

%=
o

Relational and equality operators


Relational and equality operators are used to compare two values and return true or false.

> - greater than o 3 > 2 , var1 > var2 < -less than o 2 < 3 , var1 < var2

>= - greater than or equal to o 3 >= 2 , var1 >= var2 <= - less than or equal to o 2 <= 3 , var1 <= var2 == - equality o 8 == 5+3 , var1 == var2 != - inequality o 7 != 5+3 , var1 != var2 === - strict equality (both value and DataType) o 8 === 5+3 , var1 === var2 !== - strict equality (both value and DataType) o 8 !== "8" (the first value is a numeric type, the second value is String type), var1 !== var2

- the (=) operator is an assignment operator, assigns a value to a variable (e.g. var a_name = 'value';).

Logical operators
The logical operators are used to compare multiple comparative statement.

&& - AND (return true if both expression are true) o (2 <= 3) && (8 > 7) || - OR (return true if at least one of the expression is true) o (2 >= 3) || (8 > 7)

Here is an example with some of the elements presented in this lesson (see the comments in code): 1. Open a new Flash document (ActionScript 3.0), right-click on Frame 1 and choose "Actions". 2. Add the following code in the "Actions panel":
3. const SHAPE:String = 'square'; // declare a constant 4. 5. // declare 2 variables 6. var side:int = 8; 7. var measure:String = ' pixels'; 8. 9. // apply operators to "side" variable 10. side += 3; // equivalent to: latura = latura + 3; 11. side--; 12. 13. // If "side" is greater than 8, apply "trace()" 14. if(side > 8) { trace(SHAPE+ ' - '+ side+ measure); }

15. Press "Ctrl+Enter" and see the result in the "Output panel". - Displays: square - 10 pixels - If the expression inside the parenthese of "if()" statement is true, the program executes the code between its curly brackets.

Conditional Statements if, else, switch


Conditional statements enable you to program a script to make decisions based on one ore more conditions. All conditional statements deal with Boolean values (true and false). They can execute certain instructions if a condition is true, and other instructions if it is false. This tutorial explains the following conditionals:

if - executes a piece of code only if a certain condition is true if ... else - executes some instructions if a condition is true, and other instructions if it's false switch - selects which piece of code to be executed ? : - conditional operator

if() statements
The syntax to create if() statements is:
if (condition) { // code to execute if the condition is true }

- "condition" can be any logical expresion. - If "condition" is true, executes the code within curly brackets. If the condition is false, the code ignores the statements within the curly brackets. Example:
var num:Number = 8; if(num > 7) { trace('Condition true'); } // Condition true

The value of "num" variable is greater than 7, so (num > 7) is true and the script executes the trace() function within curly brackets. if() ... else statement By adding the else keyword, you can add a block of code that will be executed only if the condition is not met. So, the "if() ... else" statement is used to execute some piece of code if the condition is true and other block of code if the condition is false. Syntax to crete "if ... else" statements
if (condition) { // code to execute if the condition is true } else { // code to execute if the condition is false }

- "condition" can be any logical expresion. Example:


var day:String = 'Monday'; if(day=='Sunday') { trace('Stay home'); } else { trace('Go to work'); } // Go to work

The script evaluates the condition within pharantesses (day=='Sunday'), which returns false becouse the value of the "day" variable is 'Monday'. Then, the script will executes the code of the "else" statement (in Output displays "Go to work"). else if() clause You can use the "else if()" clause to add and check another clause if the first "if()" statement isn't true. - Syntax:
if (condition1) { // code to execute } else if (condition2) // code to execute } else if (condition3) // code to execute condition3 is true } else { // code to execute } if the condition1 is true { if the condition1 is false and condition2 is true { if the condition1 and condition2 are false and

if all these conditions are false

So, with "else if" you can handle several different conditions. You can use as many "else if" clauses as you want. - Example:
var day:String = 'Monday'; if(day=='duminica') { trace('Stay home'); } else if(day=='Monday') { trace('Go to grandparents'); } else if(day=='Saturday') { trace('Sport'); } else { trace('Go to work'); }

// Go to grandparents

The script checks if the first "if()" condition is true, if returns false, it evaluates the next "else if" clause, if returns true executes its code and ignores the next "else if" statements, if it returns false, will check the next "else if()" clause, and so on till the "else" statement. The script above outputs "Go to grandparents", becouse the value of "day" variable is 'Monday'.

switch statement
This conditional selects one of many blocks of code to be executed, by comparing the value of a single variable against several possible values. The switch() statement makes a good alternative when you have multiple conditions to check, best used in place of a long "if-else if-else" conditional. Syntax to create switch() statements:
switch (variable) { case value1: code to execute break; case value2: code to execute break; case value3: code to execute break; default : code to execute }

if variable = value1 if variable = value2 if variable = value3 if none of the other cases match

The "switch()" statement checks the actual value of the "variable", compares it to the list of options (case), and determines the appropiate code block to execute. The "default" is used when none of the other cases match. It's not required, but it is useful if you want to define a case that executes if none of the other cases in the switch statement match. Notice that break statements are used after each "case". The break statement tells the conditional statement (or loop) to cancel the rest of its operation without going any further. If you not add the "break" instruction, the code continues to the next cases. - Example:
var day:String = 'Tuesday'; switch(day) { case 'Sunday': trace('Stay home'); break; case 'Monday': trace('Go to grandparents'); break; case 'Tuesday': trace('A walk in the garden'); break; case 'Saturday':

trace('Sport'); break; default: trace('Go to work'); }

- This code will output "A walk in the garden". Logical operators and conditionals The logical operators are: && (AND), and || (OR). They are used to evaluate multiple conditions in a conditional statement, and return true or false.

exp1 && exp2 - returns true if both "exp1" and "exp2" are true, otherwise, false o 3>2 && 5<=8 - True (both expressions are true) exp1 || exp2 - returns true if at least one of the "exp1" and "exp2" is true, otherwise, false o 3>2 || 5>=8 - True (the 3>2 is true) exp1 && exp2 || exp3 - returns true if (exp1 && exp2) or "exp3" is true, otherwise, false o 3<2 && 5>8 || 4<9 - True (the 4<9 is true)

- Example:
var day:String = 'Saturday'; var num:Number = 8; if(day=='duminica' && num==8) { trace('Stay home'); } else if(day=='Saturday' || num>8) { trace('A walk in the garden'); } else { trace('Go to work'); } // A walk in the garden

In the Output panel displays "A walk in the garden", becouse the condition "(day=='duminica' && num==8)" returns false (not both expressions true), but the condition "(day=='Saturday' || num>8)" returns true. The conditional operator ( ? : ) Another method that you can use to check the truth of an expression is the conditional operator ( ? : ). This opoerator can be used to assign a value to a variable based on a condition. - Syntax:
variable = (condition) ? val1_true : val2_false;

- It evaluates the condition, if it's True then the variable takes the value 'val1_true', otherwise, takes the value 'val2_false'. Example:
var num:Number = 8.3; // set "str" variable depending on the value of "num"

var str:String = (num > 5) ? 'www.marplo.net' : 'coursesweb.net'; trace(str); // www.marplo.net /* Equivalent with: if(num > 5) { var str:String = 'www.marplo.net'; } else { var str:String = 'coursesweb.net'; } */

- Will set "str" to "www.marplo.net" or "coursesweb.net" depending on the value of "num". The Output is "www.marplo.net". The "? :" conditional operator can also be used to determine the execution of a function or another, depending on the result of a logical expression:
(logical-expression) ? functionTrue() : functionFalse();

Example:
(var1 == var2) ? fTrue() : fFalse();

- If "var1" equal to "var2", calls the fTrue() function, otherwise calls the fFalse() function.

For loops in ActionScript 3


For loops can be useful for repeating an action multiple times. In ActionScript we can use the following repetitive for() instructions:

for() - executes a block of code a specified number of times, also it can loop through the items in an Array. for..in - loops through the elements of an array or through the properties of an object. for each..in - provide access to the property values of an object.

for loop
The for() loop is used to run a block of code a specific number of times. It has the following syntax:
for (var i:int=nr_start; i<nr_end; i++) { // code to execute }

Or this:
var i:int; for (i=nr_start; i<nr_end; i++) { // code to execute }

- var i:int=nr_start; - sets a counter variable and the starting value for our count. This will be the number that counts up during each loop. - i<nr_end; - represents the condition for the loop to continue running. It sets the ending value for our count. - i++; - tells the for loop what to do at the end of each loop. In this case increments the value of "i" by 1.

You can use any valid variable name for the name of the counter, but commonly the programmers use "i".

Let's see a simple example with a for loop:


var total:int = 1; // executes a for loop 4 times for(var i:int=0; i<4; i++) { // doubles the value of "total" and output it total *= 2; trace(total); } // In Output panel displays: 2 4 8 16

When this script executes the for() loop, first sets the counter variable (var i:int=0). Then, the second statement checks the condition (i<4), which is true and executes the code within curly brackets. Then, the "i++" statement increments the value of "i" by 1, and it checks again the condition. The condition returns true becouse the value of i is 1, the scripts executes again the code within curly

brackets, and so on, the cycle repeats until the condition returns false (in this case when the value of "i" is 4). In Output panel displays: 2 4 8 16 break instruction If you want to stop a loop statement before the condition returns false, you can use the break instrucion. This instruction tells the script to end the loop statement, like in the next example:
var total:int = 1; // executes a for loop 4 times for(var i:int=0; i<4; i++) { // ends the loop when i=2 if(i==2) { break; } // double the value of "total" and output it total *= 2; trace(total); } // In Output panel displays: 2 4

- The "if(i==2) { break; }" within the for() loop tells the script to end the loop when the value of "i" is 2, even if the condition (i<4) is true. In the Output panel displays: 2 4. When the loop ends, the other instructions within the for() body, after the "break" statement, are no more executed. The for() instruction can be used to loop through every item in an array. Example:
// create an Array var arr:Array = ['site', 'courses', 'tutorials']; // create a for() instruction to loop through the items in the "arr" Array for(var i:int=0; i<arr.length; i++) { // displays in Output the value of the current item in "arr" trace(arr[i]); } // In Output: "site courses tutorials"

- In this example, we're looping through every item in the "arr" array, "arr[i]" gets the value of the element with index "i", and the trace() function outputs its value. for..in loop The for..in loop is used to iterate over the elements of an Object or an Array. With this statement you can get the name of the properties of an Object (or the indexes of an Array), and perform an operation on each element.

The "for..in" loop has the following syntax:


for (var element:String in anObject) { // do some actions }

- The element variable is the name of the property or function contained in anObject as a string. For each iteration of the loop, the variable is set to the next property of the object. The loop runs until reaches the last element in "anObject", or until the execution of the loop ends with a "break" instruction. Let's see an example. We create an object with three properties and use a "for..in" loop to output the name and the value of each property.
// define an object var obj:Object = {'site':'coursesweb.net', 'gen':'courses', 'web':'tutorials'}; // create a "for..in" loop to iterate over "obj" properties for(var elm:String in obj) { // use trace() to output the name and the value of the property trace(elm+ ' - '+ obj[elm]); } // in Output displays: gen - courses site - coursesweb.net web - tutoriale

The "elm" variable contains the name of the property, "obj[elm]" returns its value. for each..in The for each..in loop is slightly different from the "for..in" loop because with "for each..in" you're iterating over property values. The "for each..in" loop has the following syntax:
for each (var element:Object in anObject) { // do some actions }

The element is the property rather than just the name of the property. Here is an example. We use the same "obj" object defined in the example above, but we apply a "for each..in" loop.
// define an object var obj:Object = {'site':'coursesweb.net', 'gen':'courses', 'web':'tutorials'}; // create a "for each..in" loop to iterate over "obj" properties for each(var elm:Object in obj) { // use trace() to output the value of the property trace(elm); } // in Output displays: courses coursesweb.net tutoriale

As you can notice, in this example the "elm" stores the property content (value), while in the "for..in" loop the "elm" contains the property name.

While and Do While While loops


The while loops are used to repeat a block of code as long as a specified condition is true. The while loops have the following syntax:
while (condition) { // codeBlock }

- If the condition is true, the code within curly brackets is executed, then the script checks again the condition, and if it is still true, "codeBlock" is executed again. This process continues until condition becomes false, or you use a "break" statement to end the loop. Example:
var total:int = 1; // define a variable (counter) to control the executions number var i:int=0; // create a while loop while(i<4) { total *= 2; trace(total); i++; // adds 1 to counter (i) } // In Output displays: 2 4 8 16

ActionScript first evaluates the condition (i<4), becouse "i=0", this condition returns true; so, ActionScript executes the loop body. The loop body sets "total" to its own value multiplied by two, then "trace(total)" output its value, and "i++" adds one to "i" (the counter). Then, ActionScript evaluates again the condition, and if it is true (now "i" is 1) executes the loop body. This process continues until the value of "i" variable is 4, which is not less than 4, so the condition is false, and the loop ends. We got the following output: 2 4 8 16

Do While
The do while loop is a variant of the "while()" loop. The difference is that "do while" loop first executes the block of code, and then evaluates the condition. The syntax is:
do { // codeBlock } while (condition);

Example:
var total:int = 1; // define a variable (counter) to control the executions number var i:int=1; // create a do..while loop do { total *= 2; trace('total is '+ total); i++; // adds 1 to counter (i) } while(i<0); // In Output displays: total is 2

This code displays in Output panel: total is 2 As you can notice, although the condition is false (i<0 , but i=1), the code within curly brackets is still executed once.

Break and Continu Break


break is an instruction that allows you to stop processing a loop (or "switch" conditional). If you want to end a loop before its condition is false, you can use the break instruction after a conditional "if()". Example:
var total:int = 1; // create a for() loop for(var i:int=0; i<4; i++) { total *= 2; if(total==8) break; // ends completely this loop trace('i='+ i+ ' - total='+ total); }

// Output:

i=0 - total=2

i=1 - total=4

When the conditional "if(total==8)" returns true, the code after the "break" will not be executed at all, and the execution of this "for()" loop ends. The Output panel displays: i=0 - total=2 i=1 - total=4 - The condition (i<4) is still true, becouse the value of "i" is 1, but the "break;" instruction ends completely this loop.

Continue
The continue instruction skips the remaining statements in the current loop and begins the next iteration at the top of the loop. The difference between "break" and "continue" is that the "break" statement ends completely the loop, while "continue" ends the current iteration only, and lets the loop to continue with the next iteration. Example:
var total:int = 1; // create a for() loop for(var i:int=0; i<4; i++) { total *= 2; // skip other actions in the current iteration when total==4 or total==8 if(total==4 || total==8) continue; trace('i='+ i+ ' - total='+ total); }

The Output is: i=0 - total=2 i=3 - total=16 - Notice that when the value of "total" is 4 or 8, the trace() statement after the "continue" instruction is not executed, but the for() loop continue with the next iterations until its condition is false.

"break and "continue" can be used with any loop statement: while(), do..while, for(), for..in, for each..in.

Creating Functions in ActionScript


A function is a set of instructions (a block of code) that are executed only when you access the functions. Functions allow you to organize your code into independent pieces that can accomplish different tasks. Functions can be used more than once within a script to perform their task. Rather than rewriting the entire block of code, you can simply call the function again.
There are two general kind of functions:

predefined - which are included in the programming language (e.g. trace(), addChild(), etc.) created by programmer: o that returns a value (uses the "return" statement) o not returns a value

Creating a Function
Functions are defined (created) using a special predefined keyword, function, followed by the function name, a set of parentheses and the function body (within curly brackets). There are two syntaxes to define a function, with, or without specifying the DataType. - The simple form (without DataType)
function functionName(param1, param2, ...) { // code to execute (the function body) }

- The complete form (with DataType)


function functionName(param1:DataType, param2:DataType, ...):fDataType { // code to execute (the function body) }

- functionName - is the name of the function. It is used when you want to run (access) the function. - param1, param2, ... - is an optional list of parameters. - DataType - specifies a type of data that the associate element can contains. - fDataType - (after the parentheses) sets the type of data that the function can return. If the function doesn't return a value (not use the "return" instruction), you can use void for fDataType. Example of a simple function:
function getMsg(msg:String) { trace(msg); }

- This function has a parameter, msg, which is defined to contain String data type. When you'll call this function, the code within curly brackets is executed (trace(msg)).

Calling a function To execute the code of a function you must call (or invoke) it, by using the function's name followed by a pair of parentheses (). - If the function is defined without parameters, use this syntas:
functionName()

- If the function has parameters, use the following syntax:


functionName(arg1, arg2, ...)

- arg1, arg2, ... - are the arguments (values) passed to the function, in order, to function's parameters. The number and type of values passed in must match the function definition. You can call a function multiple times. The code of the function is executed in the location where we invoke it. In the next example we create a function with a String parameter, and then we call it two times (using a direct value for the argument, and a value contained in a variable):
// define the function function getMsg(msg:String) { trace(msg); } var site:String = 'coursesweb.net'; // calling the function two times getMsg('Welcome to'); getMsg(site); // define a String variable

When the getMsg() function is called, the value of the argument is passed to the function. The function stores this value in the "msg" parameters, and use it in its code. - If you add this function in the Action panel of a new Flash document, and press "Ctrl+Enter", the Output panel will show the following result: Welcome to coursesweb.net Using the return A return statement is used to specify a value that a function returns when is called. The "return" keyword must be followed by the value that you wish to return. The syntax for creating a function that returns values is:
function functionName(param1:DataType, param2:DataType, ...):fDataType { // code to execute return someValue; }

- someValue can be a primitive (a string, a number, a boolean), a variable, or a expresion. - The "fDataType" is optional. If you add it, the data type of "someValue" must match the "fDataType". You place the return statement as the last line of the function (before the closing curly bracket), becouse

when a return statement is executed in a function, the function ends and the rest of the code is not processed. The value returned by a function can be assigned to a variable, like in the following example:
// define a function with two numeric parameters, and returns the value of a variable function addAB(a:Number, b:int) { // sets a variable to store the result of a+b var c:Number = a+b; return c; } // calling the addAB() and store the result in a variable var adds = addAB(7.5, 8); trace(adds); // output the value of "adds": 15.5 // return the value of 'c'

- The "adds" variable stores the value returned by the function. The trace function will output this value: 15.5.

You can use the return statement in any function, with, or without parameters.
Defining a return type When you define a data type for a parameter with the colon (:) after the parameter name, it indicates what kind of information should be stored in the parameter. When you add a DataType after the parentheses of a function, it specifies wat kind of data the function can return. The Data Type can be any kind of data used for variables (String, Number, int, ...). If you are unsure what type of data the function will return, you can use the wildcard data type (*), which represents untyped data. This will allow the function to return any type of data. In the next example we use the same function defined in the example above, but this time we set a data type for the value that the function will return.
// define a function with two numeric parameters, and returns a int data type function addAB(a:Number, b:int):int { // sets a variable to store the result of a+b var c:Number = a+b; return c; } // calling the addAB() and store the result in a variable var adds = addAB(7.5, 8); trace(adds); // output the value of "adds": 15 // return the value of 'c'

- ":int" after the function's parentheses force the function to return only integer values. - 7.5+8 = 15.5, but the function returns only the integer part (15). So, if you specify or not a return DataType can determine the result of the function. Functions which not have a return statement can use a data type of void.
function functionName(param1, param2, ...):void { // code to execute, but without return }

Functions - Adv anced Use


In this lesson there are presented more advanced things about using functions. The exemples in this tutorial use an Instance of a Movie Clip symbol created on the Stage (in Flash). So, before to start testing the exemples below, open a new Flash document, select "Rectangle tool" and draw a rectangle on the Stage, then convert it in Movie Clip symbol (from Modify -> Convert to Symbol, and for Type select "Movie Clip"). Make sure the object is selected, open the "Properties panel" and add a name for this instance, testClip, like in the picture below.

Setting parameters with default value In ActionScript 3.0, you can set default values for a function's parameters. To do this, simply add an equal sign (=) and the default value after an parameter name, as follows.

function sayHy(name:String = 'You') { trace('Nice to meet '+ name); } sayHy('Marius'); // displays: Nice to meet Marius sayHy(); // displays: Nice to meet You

- As you can see, the parameter with a default value becomes optional, you can call the function without adding an argument for that parameters. If you not pass an argument, the function will use it with the default value.

All parameters that have a default value must be placed last in the order of arguments. function setAccount(name:String, pass:String, email:String = null)

Let's test another example, using the "testClip" instance (the rectangle created at the beginning of this lesson). In the same document in which you have created the rectangle, right-click on Frame 1 in the Timeline, and choose Actions. Then, in the "Actions panel" add the following code:
// define a function with 2 parameters, the second is default function testF(dy:Number, rotatie:int = 45):void { // sets "y" and "rotation" properties for "testClip" instance testClip.y = dy; testClip.rotation = rotatie; } // call the function, passing only the required argument (dy) testF(10);

- "testClip.y" sets the Y distance, "rotation" is a property used to rotate the object. Press "Ctrl+Enter" to see the effect of this script. The Flash player will position and rotate the rectangle, like in the image below.

To download the FLA file with this example, click testClip Example. Using the rest parameter (...) ActionScript 3.0 adds a new feature called the rest parameter. The "rest parameter" is a symbol (...) that represents a variable number of arguments as an array followed by a name for that array (... array_name). "array_name" will be used for the array containing the values. The rest parameter allows you to call a function with as many arguments as you like; their values will be stored in the "array_name" Array. Here is an example (it uses the same document in which you have created the "testClip" instance). - Right-click on Frame 1, and choose Actions. Then, in the "Actions panel" delete any existing code and add the following code:
// define a function with "rest parameters" function testF2(... nums):void { // declare a variable which will be used to store the sum of the values passed in arguments var latura:Number = 0; // define a "for each..in" to access each value stored in "nums" Array for each (var num:Number in nums) { latura += num; // add the current value to "latura } // uses the variable, "latura" to set the 'width' and 'height' for "testClip"

testClip.width = latura; testClip.height = latura; } testF2(8, 20, 40, 50); arguments // calls the functions with multiple

- All values passed to the "testF2()" function are stored in the "nums" Array. - The "width" and "height" properties sets the width and the height of the object (in this case with a value of 118, 8+20+40+50 = 118). Press "Ctrl+Enter" to see the result. The rectangle on the stage becomes a square, like in the picture below.

To download the FLA file with this example, click testClip Example 2.

The rest parameter can also be used with other required parameters. The required parameters will have their own names and will exist independent of the rest array. Any additional arguments passed after the required ones will be stored in the rest array. function test(param1, ... rest_array)
Assign function to a variable Another way to define a function is to assign it to a variable of type Function. The syntax is:
var someVariabe:Function = function (param1, param2, ...) { // code to execute }

- Once assigned, the function can then be invoked through that variable, as in:
someVariabe(arg1, arg2, ...)

Because the function is assigned to a variable, it resides in memory as any normal variable. So, the value of this variable can be changed or deleted. Example: - Add the following code in the Flash document in which you have created the instance "testClip" (delete any other ActionScript code in Actions panel), then press "Ctrl+Enter".
// define a function with 3 parameters in a variable var vrF:Function = function (obj:MovieClip, sx:Number, sy:Number):* { // "obj" must be the instance of a MivieClip // define "scaleX" and "scaleY" properties for "obj obj.scaleX = sx; obj.scaleY = sy; } // call the function, passing the 'testClip' instance for the "obj" parameter vrF(testClip, 2.5, 1.4);

- the variable name (vrF) its the name used to call the function. - "scaleX" and "scaleY" multiply the width and height of the object. Variables and Functions The variables declared outside a function (before the function definition) can be used in the function code. The variables created within a function can only be used inside the code of that function. These variables are called "local variables", and they not exists outside the function. Example (see the comments in code):
var ext_vr:int = 18; // variable created outside any function

// define a function which use the "ext_vr" variable function oFunctie():Number { // create a local variable var in_vr:Number = 7; // add the value of the external variable "ext_vr" to the local variable in_vr += ext_vr; return in_vr; } trace(oFunctie()); function (25) // displays in Output the value returned by the // return the values of "in_vr"

// Try to access the local variable "in_vr" outside the function (delete "//") // trace(in_vr);

- Notice that the oFunctie() can use the value of the external variable "ext_vr". But if you try to access the local variable "in_vr" outside the function (deleting the "//" before trace(in_vr);), you'll get an error message. Recursive Functions A recursive function is a function that calls itself. To avoid infinite recursion (when a function never stops calling itself), use an "if()" condition to control when a recursive function calls itself. One classic use of the recursive functions is to calculate the mathematical factorial of a number, which is the product of all positive integers less than or equal to the number (1*2*3*4*...*n). In the next example it is created a recursive function to calculate the mathematical factorial of a number passed in argument.
// define a recursive function function factorial(n:uint):uint { // if n>0, multiply 'n' auto-calling function if(n > 0) { return (n * factorial(n-1)); } else { return 1; } // return 1 when n>0 is false } // store in a variable the value returned by factorial(8) var fact:uint = factorial(8); trace(fact); // Output: 40320

String Objects
Strings can be any piece of textual data : words, characters, numbers or paragraphs; added between quotes (single or double). Everything in ActionScript 3.0 is an object, including strings. When you type a string like "Have a good life" you're creating an instance of the String class.

You can create a variable that contains Strings data type by using any of the following syntaxes: var var_name:String = "Some text"; var var_name:String = new String("Some text"); var var_name:String = String("Some text"); Quotes tell the program that the text contained within them should be interpreted as a String. You can use single or double quotes, doesn't matter, but how you use them does. If your text contains double quotes, add it between single quotes. And vice versa, if your text contains single quotes, add it between double quotes. - For example:
var str1:String = "Free 'Courses' coursesweb.net"; var str2:String = 'Free "Courses" www.marplo.net';

Using escaped characters If you want to add the same quote mark within a string, the quotes contained in text must be escaped (preceded by a backslash (\)). This tells the compiler to interpret the escaped quote as part of the text, not as the end of the string. - For example:
var str1:String = "Free \"Courses\" coursesweb.net"; var str2:String = 'Free \'Courses\' marplo.net';

Escaped caracters are specific characters preceded by backslash (\). They tell the program to replace them with the real characters. There are several escape characters:

\b - Backspace character. \f - Form feed character. This character advances one page and is rarely used. \n - Adds a new line. \t - Tab character. \unnnn - Inserts a character with the four-digit hexadecimal Unicode code you specify. (e.g., "\u0278" adds ''). \xnn - Inserts a character with the two-digit hexadecimal ASCII code you specify. (e.g., "/x25" adds '%'). \' - Single quote (') character. \" - Double quote (") character. \\ - backslash (\)

To join multiple strings together, use the addition (+) operator:


var str1:String = ' Lessons '; var str2:String = 'Tutorials'; var str3:String = 'Courses'+ str1+ str2; trace(str3); // Courses Lessons Tutorials

Properties and Methods of the String object


ActionScript has special properties and methods for working with strings, which can make various handling operations, searching terms, conversions. The String object has only one property, length. This property returns an integer specifying the number of characters in string. - Example:
var str:String = "Any text"; trace(str.length); // 8

Methods
charAt(index) - returns the character in the position specified by the "index" parameter.
var str:String = "Some text"; trace(str.charAt(3)); // e

charCodeAt(index) - returns the numeric Unicode character code of the character at the specified "index".
var str:String = "Un sir"; trace(str.charCodeAt(3)); // 115

concat('str1', 'str2', ...) - appends the arguments to the end of the string (converting them to strings if necessary), and returns the resulting string.
var str:String = "Test "; trace(str.concat('str1', ' str2')); // Test str1 str2

fromCharCode(code1, code2) - returns a string comprising the characters represented by the Unicode character codes in the parameters.
trace(String.fromCharCode(115, 118)); // sv

indexOf('substring', startIndex) - searches the string and returns the position of the first occurrence of "substring" found at or after "startIndex" within the calling string.
var str:String = "Tutorials"; trace(str.indexOf('tor')); // 2

lastIndexOf('substring', startIndex) - searches the string from right to left and returns the index of the last occurrence of "substring" found before startIndex.
var str:String = "Tutorials, in online courses"; trace(str.lastIndexOf('in')); // 17

match(pattern) - matches the specifed "pattern" against the string.


var str:String = "Tutorials, tutor, courses"; var exp:RegExp = /tu[a-z]+/gi; trace(str.match(exp)); // Tutorials,tutor

replace(pattern, 'repl') - matches the specifed pattern against the string and returns a new string in which the match of "pattern" is replaced with the content specified by "repl".
var str:String = "Tutorials, tutor, courses"; var exp:RegExp = /tu[a-z]+/gi; trace(str.replace(exp, 'Lessons'));

// Lessons, Lessons, cursuri

search(pattern) - searches for the specifed "pattern" and returns the index of the first matching substring.
var str:String = "Tutorials, tutor, courses"; var exp:RegExp = /r[is]/i; trace(str.search(exp)); // 4

slice(startIndex, endIndex) - returns a string that includes the "startIndex" character and all characters up to, but not including, the "endIndex" character.
var str:String = "ActionScript free online"; trace(str.slice(13, 17)); // free

split('sep') - splits a string into an array of substrings by dividing it wherever the "sep" parameter occurs.
var str:String = "Free-online-ActionScript"; trace(str.split('-')); // Free,online,ActionScript

substr(startIndex, len) - returns a substring consisting of the characters that start at the specified "startIndex" and with a length specified by "len".
var str:String = "http://www.marplo.net"; trace(str.substr(11, 6)); // marplo

toLowerCase() - returns a copy of this string, with all uppercase characters converted to lowercase.
var str:String = "Tutorials, Courses ONLINE"; trace(str.toLowerCase()); // tutorials, courses online

toUpperCase() - returns a copy of this string, with all uppercase characters converted to uppercase.
var str:String = "Tutorials, Courses ONLINE"; trace(str.toLowerCase()); // TUTORIALS, COURSES ONLINE

toString() - converts the object into string.


var nr:int = 7; var str:String = '8'; trace(nr.toString()+ str);

// 78

(or String(nr)+ str )

Number('str') - converts the 'str' string into number.


var nr:int = 7; var str:String = '8'; trace(nr+ Number(str));

// 15

Number and Math in Action Script 3


Number object
Numbers are any number which is not included within quotes (if you add a number between quotes, will be interpreted as a String). There are several types of numbers: - Natural numbers - positive whole numbers (8, 15, 89, 1234). - Integer numbers - whole numbers that might be either positive or negative (-78 , -3 , 0 , 5 , 78). - Floating-point numbers (-6.4 , 0.8 , 12.5). - Hexadecimal numbers (0x7d8 is number 2008). - Exponential numbers - used for large numerical values ( 7.8e+8 = 780 000 000, is 7.8x108 ).

Everything in ActionScript 3.0 is an object, including numbers. In ActionScript there are special classes for working with numbers. You can create a variable that contains numerical values by using any of the following syntaxes: var var_name:NumberType = number; var var_name:NumberType = new NumberType(number); var var_name:NumberType = NumberType(number);

- NumberType represents the ActionScript class for the type of numbers that are stored in the "var_name" variable, can be 3 types:

Number - for any type of numbers: integers, decimal (floating-point), hexadecimal and exponentials. int - for integer numbers (positive or negative). uint - for positive integer numbers.

- Usually the first syntax is used. Example:


var num1:int = 78; var num2:Number = new Number(68.8); var num3:uint = uint(23);

NaN - Not a number If you declare a Number type variable, without assign a value, the variable will have the defaul value, NaN (which represents "not a number"). Mathematical operations with non-real or undefined results also yield NaN, such as the square root of -1 or zero divided by zero. Example:
var num1:Number; var num2:Number = 0/0; trace(num1); trace(num2); // NaN // NaN

To check if a variable has the NaN value, use the isNaN(num) function. This function returns true if the value of "num" parameter is NaN, otherwise, returns false. Example:
var num:Number; trace(num); trace(isNaN(num)); // NaN // true

// check if the value of "num" is NaN, and assign a numeric value if(isNaN(num)) { num = 78; } trace(num); // 78

Other things about numbers in ActionScript


- var num:Number = .4; and var nr:Number = 0.45; represent the same number (0.45). - The default value for int and uint types is 0. - To define a color in ActionScript, it uses the expression: 0xFFRRGGBB (F - alpha (transparency), R - red,

G - green, B - blue), this is a 32-bits value which can be stored in uint variable (e.g., var getcolor:uint = 0xafe8edfe; ). Methods and Constants of the Number object The Number object has no specific properties, but has a few methods and constants. To perform arithmetic operations with numbers, use the arithmetic and relational operators (see the lesson Constants and Operators).

Methods
toExponential(dg) - returns a string representation of the number in exponential notation. The "dg" parameter represents the number of digits before the decimal point.
var nr:Number = 123456789; trace(nr.toExponential(2)); // 1.23e+8

toFixed(dg) - returns a string representation of the number in fixed-point notation. The "dg" parameter represents the number of digits before the decimal point.
var nr:Number = 12.3456789; trace(nr.toFixed(3)); // 12.346

toPrecision(dg) - returns a string representation of the number either in exponential notation or in fixedpoint notation. The string will contain the number of digits specified in the "dg" parameter.
var nr1:Number = 12.3456789; trace(nr1.toPrecision(4)); var nr2:Number = 123400000; trace(nr2.toPrecision(4)); // 12.35 // 1.234e+8

toString() - converts the object into string.


var nr:int = 7; var str:String = '8'; trace(nr.toString()+ str);

// 78

(or String(nr)+ str )

Number('str') - converts the 'str' string into number.


var nr:int = 7; var str:String = '8'; trace(nr+ Number(str));

// 15

Constants
MAX_VALUE - the largest posible number
trace(int.MAX_VALUE); // 2147483647

trace(uint.MAX_VALUE); trace(Number.MAX_VALUE);

// 4294967295 // 1.79769313486231e+308

MIN_VALUE - The smallest representable number


trace(int.MIN_VALUE); trace(uint.MIN_VALUE); trace(Number.MIN_VALUE); // -2147483648 // 0 // 4.9406564584124654e-324

NEGATIVE_INFINITY - represents the negative infinity. It can be used to check the negative infinite conditions.
var nr:Number = -7/0; trace(); // -Infinity trace(nr == Number.NEGATIVE_INFINITY);

// true

POSITIVE_INFINITY - represents the positive infinity. It can be used to check the positive infinite conditions.
var nr:Number = 8/0; trace(); // Infinity trace(nr == Number.POSITIVE_INFINITY);

// true

Math class
The Math class contains methods and constants to perform complex mathematical operations. To apply the methods of the Math class, use the following syntax:
Math.method(parameter)

- Example:
var nr:Number = Math.pow(3, 4); trace(nr); var nr2:Number = Math.random(); trace(nr2); // 3 raised to power 4 // 81 // get a random value between 0 and 1 // 0.32177373580634594

Math mehods for Arithmetic operations


pow(a, b) - "a" raised to "b" power exp(a) - "e" raised to the "a" power floor(num) - "num" rounded down ceil(num) - "num" rounded up round(num) - "num" rounded to the nearest integer max(a, b, c, ...) - maximum of the set "a, b, c, ..." min(a, b, c, ...) - minimum of the set "a, b, c, ..." sqrt(num) - square root of "num" abs(num) - absolute value of "num" log(num) - logarithm (base 10) of "num"

ln(num) - natural logarithm (base e) of "num" random() - returns a random value between 0 and 1

Math mehods for Trigonometric calculations


sin(a) - Sine of an angle measuring "a" radians cos(a) - Cosine of an angle measuring "a" radians tan(a) - Tangent of an angle measuring "a" radians asin(a) - Angle in radians whose sine is "a" (arcsine of "a") acos(a) - Angle in radians whose cosine is "a" (arccosine of "a") atan(a) - Angle in radians whose tangent is "a" (arctangent of "a") atan2(x, y) - Angle which, drawn from the origin (0, 0), intersects the point (x, y) (arctangent of y/x)

- All trig functions operate on radians, an angular unit in which 2 radians measure a full revolution. To get the radians value when you know the degrees, use the following formula:
radians = degrees * Math.PI/180;

- Example:
var degrees:Number = 45; var radians:Number = degrees * Math.PI/180; trace(radians); // 0.7853981633974483

To get the degrees when you know the radians value, use the following formula:
degrees = radians * 180/Math.PI;

- Example:
var radians:Number = 0.7854; var degrees:Number = radians * 180/Math.PI; trace(degrees); // 45

Math Constants
Constants contain a fixed value. To apply a constant, use the following syntax:
Math.CONSTANT

- Example:
trace(Math.PI); trace(Math.E); // 3.141592653589793 // 2.71828182845905

E - the base of natural logarithms ( 2.71828182845905 )

LN10 - natural logarithm of 10 ( 2.302585092994046 ) LN2 - natural logarithm of 2 ( 0.6931471805599453 ) LOG10E - the base-10 logarithm of the constant e (Math.E) ( 0.4342944819032518 ) LOG2E - the base-2 logarithm of the constant e ( 1.442695040888963387 ) PI - the ratio of the circumference of a circle to its diameter ( 3.141592653589793 ) SQRT1_2 - square root of one-half ( 0.7071067811865476 ) SQRT2 - square root of 2 ( 1.4142135623730951 )

Date and Time


To work with dates and times in ActionScript, you use the Date object. To use this object, you first must create an instance of the Date class, then you can access its properties and methots to manipulate dates and times in your code. The general syntax to create a Date object is:
var obj_name:Date = new Date();

This code stores in the "obj_name" variable the curent date and time. It uses the date and time set on the client computer (the visitor). - Example:
var dat:Date = new Date(); trace(dat); // Tue Nov 9 09:58:18 GMT+0200 2010

The date represents a point in time. The "new Date()" expression gets the instant in which the Date object was created. But you can also add within parentheses a series of values for the year, month, day of the month, hour, minute, second, and millisecond to create a Date object that represents any point in time. The syntax is:
var obj_name:Date = new Date(year, month, day_month, hour, minute, second, millisecond);

- You must include at least two values, the "year" and the "month" are required, the other parameters will have the defaul value, 0. The index (value) for the first month in the year (January) is 0, and 11 is the value used for the last month (December). new Date(0) represents the 0 Unix time (January 1 1970). - Example:

var dat:Date = new Date(2010, 0, 15); trace(dat); // Fri Jan 15 00:00:00 GMT+0200 2010 var dat2:Date = new Date(2010, 11, 15, 18, 22, 32, 88); trace(dat2); // Wed Dec 15 18:22:32 GMT+0200 2010

Another way to create a Date object with a certain point in time is by passing it a single String argument representing a point in time. The string must contain a year, month, and day of the month, at minimum, and can contain more. - Examples:
var dat1:Date = new Date('1/15/2010'); // Month/Day/Year trace(dat1); // Fri Jan 15 00:00:00 GMT+0200 2010 var dat2:Date = new Date('Sun Jan 28 2007'); trace(dat2); // Sun Jan 28 00:00:00 GMT+0200 2007 var dat3:Date = new Date('15 Oct 1976'); trace(dat3); // Fri Oct 15 00:00:00 GMT+0300 1976 var dat4:Date = new Date('Sun Jan 28 2007 14:16:12'); trace(dat4); // Sun Jan 28 15:16:12 GMT+0200 2007

If the date and time in the string doesn't have a valid time format, the Date object will return NaN. To check if a Date object contains a valid date, use the isNaN() function, like this:
isNaN(obj_date.valueOf())

- This expresion returns true if the value of the argument within parentheses is a number, else, returns false. Example:
var dat:Date = new Date('Yesterday'); trace(dat); // Invalid Date trace(isNaN(dat.valueOf())); // true

So, if isNaN() returns true, that dateObject is not a valid date.

The Time zone can be local time, appears as GMT, or Universal Time, abbreviated UTC (civilian time over the meridian 0, determined by astronomical measuring).
Date object Properties and Methods Once you have a date stored in a Date variable, you can work with it and set or read any unit of time, in either UTC or in the local time zone. ActionScript has several properties and methods for working with a Date object. For example, if you want to access the current hour, you can use the getHours() method (or "hours" property), and to access the day of the month, you can use the date property (or "getDate()" method), like in the example below:
// create a Date object, for the current date time var dat:Date = new Date();

// gets the hour var hour:int = dat.getHours(); // gets the day of the month var day:int = dat.date; // Output the curent day and hour trace(day); // 19 trace(hour); // 8

// or dat.hours; // or dat.getDate();

Also, you can use the properties and methods of Date class to change any unit in a Date object. See the following example:
// create a Date object, for a specific date and time var dat:Date = new Date('Sun Jan 28 2007 14:16:12'); // set a new value for the day of the month dat.date = 11; // or dat.setDate(11); // set a new value for hour dat.setHours(8); // or dat.hours = 8; // Output the new date trace(dat); // Thu Jan 11 08:16:12 GMT+0200 2007

The day of the month is set 11 (initialy 28), and the hour, 8 (initialy 14). The program automaticaly changes the day of the week according with the new settings (from "Sun" to "Thu").

Date Properties

date - The day of the month (from 1 to 31) dateUTC - The day of the month (from 1 to 31), according to universal time (UTC) day - The day of the week (0 for Sunday, 1 for Monday, and so on) dayUTC - The day of the week (0 for Sunday, 1 for Monday, and so on), according to universal time (UTC) fullYear - The full year (a four-digit number, such as 2012) fullYearUTC - The full year (a four-digit number, such as 2012), (UTC) hours - The hour (from 0 to 23) hoursUTC - The hour (from 0 to 23), UTC time milliseconds - The milliseconds (from 0 to 999) millisecondsUTC - The milliseconds (from 0 to 999), according to universal time minutes - The minutes (from 0 to 59) minutesUTC - The minutes (from 0 to 59), according to universal time month - The month (0 for January, 1 for February, and so on) monthUTC - The month (0 for January, 1 for February, and so on), UTC time seconds - The seconds (from 0 to 59) secondsUTC - The seconds (an integer from 0 to 59), according to universal time time - The number of milliseconds since midnight January 1, 1970, universal time timezoneOffset - The difference, in minutes, between universal time (UTC) and the computer's local time.

Date Methods

getDate() - Returns the day of the month based on the viewer's local time (1-31) getDay() - Returns the day of the week (0 for Sunday, 1 for Monday, and so on) getFullYear() - The full year based on the viewer's local time (four digits) getHours() - Returns the hour, based on the viewer's local time (0-23) getMilliseconds() - The number of milliseconds into the current second in Coordinated Universal Time (0-999) getMinutes() - Returns the minutes (from 0-59) getMonth() - Returns the month (0-11) getSeconds() - Returns the seconds (from 0 to 59) getTime() - The number of milliseconds since 1/1/1970 getTimezoneOffset() - Returns the time difference (in minutes) between GMT (Greenwich Mean Time) and local time getUTCDate() - The day of the month in UTC, (1-31) getUTCDay() - Returns the day of the week, according to universal time (0-6) getUTCFullYear() - The full year in UTC, (four digits) getUTCHours() - Returns the hour, according to universal time (0-23) getUTCMilliseconds() - The number of milliseconds into the current second in Coordinated Universal Time (0-999) getUTCMinutes() - The number of minutes, in UTC (0-59) getUTCMonth() - The number of months into the current year in UTC (0-11) getUTCSeconds() - The number of seconds in Coordinated Universal Time (0-59) parse("string_date") - Returns the number of milliseconds since 1/1/1970 of a date sent as a parameter ("string_date") based on the viewer's local time setDate(day) - Sets the day of the month for an instance of the Date class (1-31) setFullYear(year, month, day) - Sets the year, according to local time, and returns the new time in milliseconds ("month", and "day" are optional) setHours(hours, minute, second, millisecond) - Sets the hours for an instance of the Date class (0-23), and returns the new time in milliseconds ("minute", "second", and "millisecond" are optional) setMilliseconds(ms) - Sets the milliseconds, with the value of "ms" parameter (0-999) setMinutes(minute, second, millisecond) - Sets the minutes in a Date object (0-59), returns the new time in milliseconds ("second", "millisecond" are optional) setMonth(month, day) - Sets the month for an instance of the Date class ("day" is optional), returns the new time in milliseconds setSeconds(second, milisecond) - Sets the seconds in a Date object ("millisecond" is optional), returns the new time in milliseconds setTime(milisecond) - Sets the time (in milliseconds since January 1, 1970, at midnight) for an instance of the Date object setUTCDate(day) - Sets the day of the month, according to universal time (1-31) setUTCFullYear(year, month, day) - Sets the year in Coordinated Universal Time (four digits), and returns the new time in milliseconds ("month", and "day" are optional)

setUTCHour(hours, minute, second, millisecond) - Sets the hour, according to universal time (023), and returns the new time in milliseconds ("minute", "second", and "millisecond" are optional) setUTCMilliseconds(ms) - Sets the milliseconds, according to universal time, with the value of "ms" parameter (0-999) setUTCMinutes(minute, second, millisecond) - Sets the minutes, according to universal time (059), returns the new time in milliseconds ("second", "millisecond" are optional) setUTCMonth(month, day) - Sets the month, according to universal time (0-11), returns the new time in milliseconds ("day" is optional) setUTCSeconds(second, milisecond) - Sets the seconds, according to universal time (0-59), returns the new time in milliseconds ("millisecond" is optional) toLocaleString() - Returns a String representation of the day, date, time, given in local time toLocaleDateString() - Returns a String representation of the day and date only, and does not include the time or timezone toLocaleTimeString() - Returns a String representation of the time only, and does not include the day, date, year, or timezone toString() - Returns a String representation of the day, date, time, and timezone toTimeString() - Returns a String representation of the time and timezone only, and does not include the day and date toUTCString() - Returns a String representation of the day, date, and time in universal time (UTC)

Flash.utils.getTimer() returns the number of milliseconds since Flash Player is running.

Array in Action Script 3


Arrays are variables that store multiple values in a single variable name. So, an Array is a variable with an ordered list of values.

Creating Array
In ActionScript 3 there are two ways to create an Array: with square brackets [] (also known as JSON syntax), and with the Array object. 1) Syntax for Array created with square brackets:
var array_name:Array = [val1, val2, ...];

2) Syntax with Array object:


var array_name = new Array(val1, val2, ...);

- "array_name" - is the name of the Array, and will be ussed to access its elements (can be any name used for variables). - "val1, val2, ..." - are the values (elements) stored in the Array. An element can be any type of value: String, Number, Object or eaven another array. For example: var m_ar:Array = ['some string', a_variable, 7.8]; OR: var m_ar:Array = new Array('some string', a_variable, 7.8);

To create an empty Array, you can use any of these two expresions: var m_ar:Array = []; OR var m_ar:Array = new Array();

Using Array elements


Once an Array is created, you can access and use its items. Arrays are structured as a series of index-value pairs, where one pair is an element of that array. For each item in the list, there is an index (an integer) associated with it. So, the array elements are stored in numerical order, starting from 0. The first element has index 0, the second index 1, and so on. To access an element of an Array, write the array name followed by the index within square brackets: array_name[index]. - Example:

var m_ar:Array = ['web site', 'coursesweb.net', 78]; // get the second item (with index 1) trace(m_ar[1]); // Output: coursesweb.net

To access the first value, use index 0 (e.g., trace(m_ar[0]); will output "web site"). An array item accessed in this way (array_name[index]) can be used as any variable, in operations with other values and variables. Also, you can use a variable for the index value. Let's see an example:
var m_ar:Array = ['web site', 'coursesweb.net', 78]; // define a variable to be used for index var i:uint = 2; // create a variable which use an array item for its value var test = 4 + m_ar[i]; trace(test); // Output: 82

- Because the value of "i" variable is 2, the expression m_ar[i] will access the third element in "m_ar" and return its value (78). Modify and Add values in an Array To modify a value in an array, assign a new value to the element with a specified index number. Syntax:
array_name[index] = new_value;

If the array_name[index] element isn't defined in that array, will be added automatically with the "new_value". This method can be used when you want to add new elements in an array. See the next example and the explanations in it:
var m_ar:Array = ['web site', 'coursesweb.net', 78]; // changes the value of the first element m_ar[0] = 'tutorials'; // use "trace(m_ar)" to check the Array values trace(m_ar); // tutorials,coursesweb.net,78 // adds a new element in "m_ar" (fourth, with index 3) m_ar[3] = 'ActionScript'; // use "trace(m_ar)" to check the Array values trace(m_ar); // tutorials,coursesweb.net,78,ActionScript

- "trace(array_name)" displays in the Output panel the values stored in array_name, separated by comma. The example above will display in Output: tutorials,coursesweb.net,78 tutorials,coursesweb.net,78,ActionScript

To delete the value of an Array element, just assign it an empty value: array_name = "";. The item will remain in the array, but with no value. To delete completely an intem from an Array, use the slice() method. Syntax:
array_name.slice(index, 1)

- "index" - is the index of the item you want to delete. The value of 1 specifies that one element will be deleted. Example:
var m_ar:Array = ['web site', 'coursesweb.net', 78]; // delete the value of the third item in "m_ar" m_ar[2] = ''; // delete the second item in "m_ar" m_ar.splice(1, 1); // use "trace(m_ar)" to check the Array values trace(m_ar); // web site,

The number of items in Array When you work with Arrays, often it is necessary to know the number of items in that array. To get the number of elements in an array, use the length property.
array_name.length

If in an Array, for example with three elements (with index 0, 1, and 2), you add a new elemant, but with a higher index that the next item should have, for example a fourth element, but with index 5, that Array will have 6 elements. ActionScript will automatically add the missing elements with an empty value, starting from the next index in array till the index of the new item. See the following example:
var m_ar:Array = ['web site', 'coursesweb.net', 78]; // define a variable to store the number of items in "m_ar" var nrel:int = m_ar.length; // use "trace(nrel)" to check the number of items trace(nrel); // 3 // add a new element in array (fourth, but with index 5) m_ar[5] = 'www.marplo.net'; // updates number of items stored in "nrel" and check again with trace() nrel = m_ar.length; trace(nrel); // 6 // check to see all values in "m_ar" trace(m_ar); // web site,coursesweb.net,78,,,www.marplo.net

As you can notice, after the fourth value was added, with index 5, the "m_ar" array has 6 elements. The items with index 3 and 4 was automaticaly added, with empty value. The example above will display in Output: 3 6 web site,coursesweb.net,78,,,www.marplo.net

The length property can also be used to set a specific number of elements in an array, adding empty values if you specify a higer index, or deleting items (starting from the last) if you set a length lower then the number of items in the array. See the following example:
var m_ar:Array = ['web site', 78, 'www.marplo.net']; // set a number of 8 items in "m_ar" m_ar.length = 8; // define a variable to store the number of items in "m_ar" var nrel:int = m_ar.length; // use "trace(nrel)" to check the number of items trace(nrel); // 8 // set a number of 2 items in "m_ar" m_ar.length = 2; // updates number of items stored in "nrel" and check again with trace() nrel = m_ar.length; trace(nrel); // 2 // check to see all values in "m_ar" trace(m_ar); // web site,78

Transverse Arrays Multi-Dimensional Array


Traversing Arrays
The elements of an Array can easily be parsed with one of these loop instructions: for(), while(), and for each..in. Traversing an Array with one of these instructions enables you to access each element in an Array, in their order. Here's an example with each of them:

Using for()
var m_ar:Array = [3, 8, 32]; var nrel:int = m_ar.length; // get the number of elements in "m_ar"

// define a "for()" loop to traverse the "m_ar" array for(var i:int=0; i<nrel; i++) { // doubles the current element value m_ar[i] *= 2; } // uses trace() to check the values in "m_ar" trace(m_ar); // 6,16,64

- var i:int=0; - sets the starting value for the index. This index specifies the element from which the for() loop begins to traverse the array (you can set any value for the starting index). - i<nrel - makes the for() loop to go through to the last element ("nrel" contains the number of items in array). - i++; - tells the for() instruction to increment the value of "i" by 1, at the end of each loop, to get the next element.

Using while()
var m_ar:Array = [3, 8, 32]; var nrel:int = m_ar.length; var i:int = 0; // get the number of elements in "m_ar" // defines the starting index

// define a "while()" loop to traverse the "m_ar" array while(i<nrel) { // doubles the current element value m_ar[i] *= 2; i++; // increments the index to go to the next item } // uses trace() to check the values in "m_ar" trace(m_ar); // 6,16,64

Using for each..in


var m_ar:Array = [3, 8, 32]; // define a "for each..in" loop to traverse the "m_ar" array for each(var elm:Number in m_ar) { // doubles the value of the current element, which is stored in "elm" elm *= 2; // you can perform operations with "elm", its value not affect the array } // uses trace() to check the values in "m_ar" trace(m_ar); // 3,8,32

- Notice that in this case the array is not affected, "elm" only gets the value of the element, and you can perform operations with it.

Multi-dimensional Array
The element in an array can be another array. In this case we are dealing with a multi-dimensional array. Let's see an exampe:
// define a simple array (which will be included in the next array) var arr:Array = [88, 'ActionScript']; // define an array with 3 elements (the third item is the "arr" variable) var m_ar:Array = ['tutorials', 'coursesweb.net', arr]; // checks the values of the main array and of the third element trace(m_ar); // tutoriale,coursesweb.net,88,ActionScript trace(m_ar[2]); // 88,ActionScript

- The array in the third element ("arr" which contains [88, 'ActionScript']) is called "nested array".

Accessing elements in a Nested Array


To access the elements of a nested array, use the following syntax:
array_name[i1][i2]

- "i1" is the index associated to the nested array, "i2" is the index of the element in the nested array. Example:
// define a simple array (which will be included in the next array) var arr:Array = [88, 'ActionScript']; // define an array with 3 elements (the third item is the "arr" variable) var m_ar:Array = ['tutorials', 'coursesweb.net', arr]; // stores in a variable the second element in the nested array var test:* = m_ar[2][1]; // check the value of the "test" trace(test); // ActionScript

Traversing a multi-dimensional Array


To traverse a multi-dimensional Array, including the nested arrays, you should use nested loop instructions, like in the following example.
// define a simple array var arr:Array = [88, 'ActionScript']; // define an array with 3 elements (the third item is the "arr" variable) var m_ar:Array = ['tutorials', 'coursesweb.net', arr]; var nrel = m_ar.lengt; // get the number of elements in "m_ar"

// create 2 nested for() loops to access each item in the multi-dimensional array for(var i:int=0; i<nrel; i++) { var elm:* = m_ar[i]; // get the current element in "m_ar" // if "elm" is an Array, define another for() loop to traverse it // else, outputs its value if(elm is Array) { for(var i2:int=0; i2<elm.length; i2++) { trace(elm[i2]); // output the value of the current element in nested array } } else { trace(elm); } }

- The "(elm is Array)" returns true if "elm" is an Array data type, else, returns false. - The first for() loop traverses the main array. If the current element is an array, the nested for() instruction is executed to access its elements (you can use any loop instruction, while(), for..in). The example above will display in Output panel: tutorials coursesweb.net 88 ActionScript

Assosiative Arrays in ActionScript 3


Associative arrays use strings in place of index numbers, to associate the value of the elements. These indexes must be specified by the programmer. - The syntax to create an associative array is:
var array_name:Array = new Array(); array_name['index1'] = value1; array_name['index2'] = value2; array_name['index3'] = value3;

- You can add as many elements as you want. - You can use either single or double quotes for "index". You can access or change the value of a specific element of an associative array the same as with a numeric indexed array, using its index: array_name['index']. The elements of an associative array can also be accessed with the dot (.) operator: array_name.index (like the proprietes of an object). Here's an example in which we apply both methods:
// associative array, with 3 elements var m_ar:Array = new Array(); m_ar['site'] = 'coursesweb.net'; m_ar['course'] = 'Adobe Flash'; m_ar['tutorials'] = 'ActionScript'; // Access the element with index 'site' trace(m_ar['site']); // coursesweb.net // Access another element, using the dot (.) operator trace(m_ar.course); // Adobe Flash

Traverse associative Arrays


You can traverse an associative array with the for..in, or for each..in loop.

Example with for..in


// associative array, with 3 elements var m_ar:Array = new Array(); m_ar['site'] = 'coursesweb.net'; m_ar['course'] = 'Adobe Flash'; m_ar['tutorials'] = 'ActionScript'; // create a "for..in" loop to traverse the "m_ar" array for(var key:String in m_ar) { // displays in Output the index and the value of the current item trace('Index='+ key+ ' - value='+ m_ar[key]);

// You can execute any operations with "key" si "m_ar[key]" }

- key is a variable which stores the "index" of the current element (you can use any name for the variable). In Output will display: Index=site - value=coursesweb.net Index=tutorials - value=ActionScript Index=course - value=Adobe Flash

Example with for each..in


// associative array, with 3 elements var m_ar:Array = new Array(); m_ar['site'] = 'coursesweb.net'; m_ar['course'] = 'Adobe Flash'; m_ar['tutorials'] = 'ActionScript'; // create a "for each..in" loop to traverse the "m_ar" array for each(var elm in m_ar) { // displays in Output the value of the current item (stored in elm) trace('valE - '+ elm); // You can execute any operations with "elm" }

Notice the diferences between "for..in" and "for each..in". The "for each..in" loop doesn't get the index of the element. The "elm" store the element itself. In Output will display: valE - Adobe Flash valE - coursesweb.net valE - ActionScript

Code Snippets Add and Create


Code Snippets are pieces of predefined code that can be reused, saved in the "Code Snippets" panel. They are organized on cathegories and functions, such as: "Animation", "Timeline Navigation", and others. You can open this panel from the Window -> Code Snippets menu, or the button "Code Snippets" found in the Actions panel (as you can see in the following image).

Flash has a few functions /codes saved in "Code Snippets". For example, to make a button execute a jump to a certain frame, instead of writing the whole code (with the necessary event and function), you can add it directly from the "Code Snippets" panel, being saved in the "Timeline Navigation" catalogue, with the name "Click to Go to Frame and Play". To add a code-snippet into your script, double-click on its name, select it and click the button "Add to current Frame". Flash has in "Code Snippets" some of the most used functions for working with ActionScript. To learn about them you must browse their list, the name with which they are saved also explains their role. Besides these predefined functions included in Adobe Flash, you can also add your own pieces of code to be stored in "Code Snippets", useful when you usually use a same code expression,

functions or any code. To add your own code in the "Code Snippets" panel, you must click on the panel's options menu (upper-right)and choose the option Create New Code Snippet, Flash will open a window as the one in the following image.

- At Title you must write the name (as suggestive as possible) that will appear for that code added in "Code Snippets". - The description that is writte at Tooltip will appear when the mouse is positioned over the name stored in the panel. - You write the ActionScript code in the text area, Code. If a certain piece of the code is already selected in the "Actions panel", use Auto-fill button to add the selected code in the "Code" area. - After pressing the OK button, the respective code is added with the name specified at "Title" in a folder named "Custom" (created automatically by Flash). Predefined codes as well as those added in "Code Snippets" are stored in a XML file. - To re-edit a Code Snippet, right-click on its name and choose Edit Code Snippets XML. This will open the XML file with all the predefined codes from the panel. Then, you must find the code in that file (with "Ctrl+F") and edit it. Then click File -> Save. - The option "Copy to Clipboard" (which appers when you right-click on a code-snippet) copies the respective code in memory, and then it can be added (with Paste) in the "Actions panel". - With "Delete Code Snippet" the respective code will be deleted from the panel. - The XML file with all the codes stored in "Code Snippets" can be exported with the option "Export Code Snippets XML". - With "Reset to Default XML" the "Code Snippets" panel is restored to it's initial predefined codes.

Detecting Events in Action Script 3


Events are actions carried out in the Flash presentation by the user or by other elements from that prezentation. For example, clicking or positioning the mouse over a Flash element, writing in a Text Input field, are events carried out by the user; and reaching a certain frame of an animation or finalizing an action are events carried out by elements in the presentation. ActionScript 3 contains special objects and methods used to detect and recognise events, depending on these certain commands, different actions can be executed when those events occur. Like most things in ActionScript 3, an event is considered an object, it has special properties and methods for working with events. In brief, an event works like this: the action tied to an element (called "event target") occurs (a pressed button, an animation, etc.) and transmits data to the script, in the form of an object (called "event object"). The script must contain a special function known as "event listener" , which detects the event and takes it's data and transmit it to a function that can perform different commands. The function /method used in in ActionScript 3 to detect and capture events is "addEventListener()". It's a method from the "EventDispatcher" class, and it records in the script to detect the action on the element indicated by it. The general syntax to use this method is:
event_target.addEventListener(EventObject.TYPE, aFunction); function aFunction(ins_EventObject:EventObject):void { // The code to execute }

- "event_target" is the object at which the event occurs (it's instance name. For example, the instance name of a button that will be pressed). - "EventObject" reprezente the cathegory of events that must be detected. It's also the object where information about the event that occured is stored (Ex., MouseEvent, TextEvent). - "TYPE" is a constant that reprezents the type of event (such as: CLICK, MOUSE_OVER, COMPLETE) from the specified cathegory. - The "event_object.TYPE" specifies exactly the event that must be recognized. Ex., "MouseEvent:CLICK" is detected when somebody click's on the "event_target", or, "Event.COMPLETE" detects when an action is completed. - "aFunction" is a function that is invoked when the event has occured, and the code in it will be executed. - "ins_EventObject" is the instance of the "EventObject" object through which the data transmited in

that object can be processed. ActionScript 3 has a multitude of events that can be recognized, such as: MouseEvent (for mouse), KeyboardEvent (for keyboard), TextEvent (for text fields), ScrollEvent (for Scroll), IOErrorEvent (for cases when errors appear), and others. The list with all types of events, properties, methods and their constants can be found at AS3 Events. Here's a practical example of using event detection. A content taken from an external TXT file will be displayed in a text field in the Flash presentation.
// Creating "event target" // An instance of the URLLoader object (used for loading data from a URL address var urlLoader:URLLoader = new URLLoader(); // Applies the "load()" method (for loading) at the URLLoader instance // creates a URLRequest instance used to specify the files address urlLoader.load(new URLRequest("somefile.txt")); // Set an "event listener", applied at "urlLoader", recognizes when the loading of the file has been completed urlLoader.addEventListener(Event.COMPLETE, campTxt); // Function that will be called by the event that was set-up function campTxt(evt:Event):void { // defines a TextField object instance to create a text field var camp_txt:TextField = new TextField(); camp_txt.x = 78; // Distance from the left edge camp_txt.y = 75; // Distance from the top edge camp_txt.width = 145; // Lenght of the text field camp_txt.height = 50; // Height camp_txt.border = true; // Activates to display the border // Adds data from the loaded file to the text field, stored in "evt" camp_txt.text = evt.target.data; addChild(camp_txt); presentation. } // Adds the text field in the flash

- First, an instance must be created using the "URLLoader" object, it is used to load the content from an external file. The URL loading adress must be added to this instance with the "URLRequest" object. Then the "addEventListener()" method is applied to the same instance and it's defined to recognize the "Event.COMPLETE" type of event (activated when a specific action is completed, here the loading). - When the loading is completed, the event registered in that instance is activated, which detects completion of the loading process. Then it takes the data and transmits them at the "campText" function, this function retains the data in the "evt" parameter, creates a text field and with the "evt.target.data" expression it adds the data in the field and displays it in the Flash prezentation. - See the explanations in the code. Add this code in a new Flash document, make the SWF presentation (with Export) and in the same folder

create a file with the name "somefile.txt" with some text in it. The result will be a flash presentation like this:

The file's URL address, added at "URLRequest("URL_fisier")", must be complete or relative to the Flash presentation, depending in which folder it's located.
Deleting event detection

To stop an "event listener" set up with "addEventListener()" from receiving notifications about the registered event, that record must be deleted, with the method "removeEventListener()" (belongs to the "EventDispatcher" class). The general formula used for this method is:
event_target.removeEventListener(EventObject.TIP, aFunction);

- "event_target" represents the instance to which the event listener "addEventListener()" was applied, that must be deleted. - "EventObject.TYPE" is the type of event. - "aFunction" is a function that was set up to be called.

It is recommended to delete the record of an event's detection, when it is not needed in the program anymore, because it help freeing up used memory. The event is permanently active and tied to the function that it calls (stored in memory) until it is deleted with "removeEventListener()".
Here's how the method must be applied to the previous example
// Creating "event target" // An instance of the URLLoader object (for loading data from a URL address) var urlLoader:URLLoader = new URLLoader( ); // Apply the "load()" method to the URLLoader instance // create a URLRequest instance used to specify file address urlLoader.load(new URLRequest("somefile.txt")); // Setting "event listener", to detect when the loading of a file has finished urlLoader.addEventListener(Event.COMPLETE, campTxt); // Function that will be called by the set event function campTxt(evt:Event):void { // defines a TextField object instance to create a text field var camp_txt:TextField = new TextField(); camp_txt.x = 78; // Distance from the left edge camp_txt.y = 75; // Distance from the top edge camp_txt.width = 145; // Lenght of the text field camp_txt.height = 50; // Height camp_txt.border = true; // Activates the display of a border // Adds data from the loaded file to the text field, stored in "evt"

camp_txt.text = evt.target.data; addChild(camp_txt); presentation. // Adds the text field in the flash

// After the field is added to the presentation // Delete the record of the event's detection, to free up memory urlLoader.removeEventListener(Event.COMPLETE, campTxt); }

- "urlLoader.removeEventListener(Event.COMPLETE, campTxt);" is added in the function "campTxt()" after the command which displays the text field with content loaded from the external file. This way, this command is executed after the event's role to take and display the loaded data ends, therefore it is no longer necessary to store it in memory. - If this instruction would have been written outside the "campText()" function, it would have as effect the deletion of the event's detection before the function would have been called and would no longer be carried out because the event would not be detected. The FLA file with this example can be downloaded from: Detecting events. Priority of event capture Normally if there are multiple event listeners registered at the same object (with equal or different types), the order of capture and triggering is the one in which they are written in the script. But this order can be changed, using a "priority parameter" in the "addEventListener()" method:
event_target.addEventListener(EventObject.TIP, oFunctie, useCapture, prioritate);

- for "useCapture" you put false - "priority" is an integer number that is equal to or greater than zero, through which the execution priority is determined (default is 0). The event listener with greater priority is triggered before others. For example, for the following 2 registered events:
urlLoader.addEventListener(Event.COMPLETE, aFunction, false, 0); urlLoader.addEventListener(Event.COMPLETE, bFunction, false, 1);

- The event with priority 1 is executed first, which calls the "bFunction" function, and then it is executed the event with priority 0.

MouseEvents Event for Mouse


The mouse pointer is the most common way through which the user interacts with the Flash presentation. The events for mouse are different actions performed with the mouse, such as clicking, positioning the pointer over an object or simply moving it. All these actions are named "mouse events" and can be detected by the class MouseEvent. The type of events for the MouseEvent:

CLICK - is triggered when the user presses and releases the main mouse button over an object in the Flash presentation DOUBLE_CLICK - is triggered when a double-click is executed on the recorded object. This object must have the doubleClickEnabled property set to true MOUSE_DOWN - detects the moment when the left mouse button is pressed (without being necessary to release the click) MOUSE_UP - executes the event when the click is released MOUSE_MOVE - the event is triggered each time the mouse pointer is moved over an objects MOUSE_OUT - the event is executed when the mouse leaves the objects area or the area of any of its "child elements" MOUSE_OVER - is triggered when the mouse enters the area of the monitored object or of any "child element" MOUSE_WHEEL - event is dispatched when a mouse wheel is spun over a monitored object in the Flash Player ROLL_OUT - it's similar to MOUSE-OUT, the difference is that the event is triggered only when the mouse completely leaves the object's area, while, the MOUSE_OUT event is thrown each time the mouse leaves the area of any child object of the display object container. ROLL_OVER - is similar to MOUSE-OVER, the difference is that the event is triggered when the mouse enters the objects area, while, the MOUSE_OVER event is thrown each time the mouse enters the area of any children of the monitored object

Here's an example with MouseEvent for CLICK, MOUSE_MOVE and MOUSE_DOWN. We create a Flash presentation with 2 Frames, in the first frame a button is added and in the second frame a geometric figure (a star). When the user presses the button, jumps to frame 2, which displays the star. When the mouse is moved over the star, it spins and shrinks, and if the user press the button (MOUSE_DOWN) over the star, jumps to the first frame. 1. Open a new Flash document ActionScript 3.0

2. Draw an oval shape on the Stage (or a rectangle), (you can also add a text on the shape, with "Text Tool"). Select the shape and convert it into a Button (from Modify -> Convert to Symbol and for Type choose Button). 3. Make sure the shape is selected, open the "Properties panel" and add the name buton in the box for "Instance Name". As you can see in the following image.

4. Right-click on frame 2 in the Timeline and choose "Insert Blank Keyframe" (a new empty frame is created), then select the "PolyStar Tool" in the Tools panel. 5. Click on the Options button in the Properties panel of the "PolyStar Tool", then, for Style choose the option star (to draw a star, you can modify the number of sides from "Number of Sides") and press OK. 6. Select a gradient color in the "Fill Color" (for a more visible effect of rotation) and draw a star on the Stage. 7. Convert the star into MovieClip (from Modify -> Convert to Symbol, and for Type choose Movie Clip and press OK), then, in the Properties panel add the name star for this MovieClip instance on the stage. 8. Create a new Layer in the Timeline (from Insert -> Timeline -> Layer) that will be used to add ActionScript codes. - You can give it a specific name (for example: "Actions" or "Scripts"), by double-clicking on its name. 9. Right-click on Frame 1 in this second Layer, choose Actions, and add the following code in the "Actions panel".
10. 11. 12. 13. 14. 15. 16. 17. 18. 19. stop(); // Stops the presentation at frame 1 // Register a mouse event ( CLICK ) for the button instance buton.addEventListener(MouseEvent.CLICK, gotoF2); // Funtion called by the registered event for 'buton' function gotoF2(event:MouseEvent):void { gotoAndStop(2); // Jumps and stops at Frame 2 }

20. Right-click on Frame 2 in this second Layer, choose Actions, and add the following code in "Actions panel".
21. // Register a mouse event ( MOUSE_MOVE ) for the star instance 22. star.addEventListener(MouseEvent.MOUSE_MOVE, rotate);

23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45.

// Register another mouse event ( MOUSE_DOWN ) for the star instance star.addEventListener(MouseEvent.MOUSE_DOWN, gotoF1); // Function called by the event MOUSE_MOVE function rotate(evt:Event):void { // Rotate the object that triggered the event evt.target.rotationZ -= 2; // If the length of the object is higger than 80 pixels // shrinks its length and height by 5 if(evt.target.width>88) { evt.target.width -= 5; evt.target.height -= 5; } } // Function called by the event MOUSE_DOWN function gotoF1(evt2:MouseEvent):void { gotoAndStop(1); // Jumps and stops at Frame 1 }

- This is used by Flash when the presentation reaches frame 2. - The "stop()" instruction in Frame 1, makes the presentation stops at the Frame 1, otherwise it would have continued with the following Frame. - the expression "evt.target" refers to the element that has triggered the event. - "evt.target.rotationZ -= 2;" rotates by 2 degrees in Z plane the object that triggered the event. - This code will display the following Flash presentation. Click on the button, move the mouse over the star, and then click on the star. To download the FLA file with this example, click: Mouse events. Mouse coordinates

You can use the MouseEvent object to capture the mouse coordinates in the Flash presentation. The MouseEvent object has the following properties used to find out the position of the mouse, relative the Stage (upper-left corner) and relative to the element that trigger the mouse event.

localX - the horizontal coordinate at which the event occurred relative to the containing sprite localY - the vertical coordinate at which the event occurred relative to the containing sprite stageX - the horizontal coordinate, reported to the upper left corner of the stage stageY - the vertical coordinate, reported to the upper left corner of the stage

Capturing these coordinates, you can execute different instructions depending on the mouse position in the Flash presentation. As you can see in the following example. Follow these steps:

1. Open a new Flash document, ActionScript 3.0 2. Draw a rectangle on the center of the stage and convert it into MovieClip (from Modify -> Convert to Symbol, and for Type choose Movie Clip, and press OK, then in the "Properties panel", add the name rectangle for the instance of this MovieClip. 3. Choose the "Text Tool" and write above the rectangle: "Coordinates in Stage", and give this text field the instance name txtS. Write below the rectangle the text "Coordinates in Rectangle", and give this text field the instance name txtD. As you can see in this image:

4. Right-click on frame 1 in the Timeline, choose Actions, and add the following code in "Actions panel":
5. // Register a mouse event ( MOUSE_MOVE ) for the rectangle instance 6. rectangle.addEventListener(MouseEvent.MOUSE_MOVE, getCoord); 7. 8. // Function called by the registered event 9. function getCoord(evt:MouseEvent):void 10. { 11. // Add in the txtS instance the coordinates of the mouse relative to the stage 12. txtS.text = 'Coordinates in the stage: '+ evt.stageX+ ', '+ evt.stageY; 13. 14. // Add in the txtD instance the coordinates of the mouse relative to the rectangle 15. txtD.text = 'Coordinates in the rectangle: '+ evt.localX+ ', '+ evt.localY; 16. 17. // Set a ColorTransform instance to change the color 18. var col:ColorTransform = rectangle.transform.colorTransform; 19. 20. // If the localX coordinate is higger than 90 (pixels) it sets the color to yellow 21. // Otherwise, it sets it to green 22. if(evt.localX>90) col.color = 0xeded01; 23. else col.color = 0x00fe00; 24. 25. // Apply the ColorTransform instance to rectangle 26. rectangle.transform.colorTransform = col; 27. }

28. Press Ctrl+Enter to test the result. The following Flash presentation will appear: - If you move the mouse over the rectangle, in the text above the rectangle will show the mouse coordinates relative to the top-left corner of the Stage, and in the text below will display the mouse coordinates relative to the top-left corner of the rectangle. - Move the mouse cursor over the rectangle to see the effect, its color will change depending on the mouse position, as it is set in the ActionScript code above. - "evt.stageX", and "evt.stageY" return the mouse coordinates (stored in "evt" object) relative to the Stage. - "evt.localX" and "evt.localY" return the mouse coords relative to the rectangle. The FLA file with this example can be downloaded from: Mouse coords.

KeyboardEvent Event for Keyboard


Keyboard Events (triggered when a key from the keyboard is pressed) are detected with the KeyboardEvent object. The KeyboardEvent comes in two types:

KEY_DOWN - dispatched when the user has pressed a key. KEY_UP - dispatched when the user has released a key..

KeyboardEvent has 6 properties:

charCode - contains the character code value of the key pressed or released. - For example: for 'a' the code value is 97, for 'A' it's 65, for '3' it's 51, and for 'Shift+3' (meaning '#') it's 35. keyCode - contains a number with the code value of the key pressed or released. The difference from "charCode" is that "charCode" returns the 0 value for the keys that do not represent a character (Shift, Ctrl, the arrows, ...), but "keyCode" contains a specific number for these keys too.

- For example: for 'Shift' it returns the number 16, for right arrow key it returns the number 31. keyLocation - contains a number that indicates the location of the key pressed or released. Used for keys that appear multiple times on the keyboard, such as: Shift, Alt. altKey - indicates true if the 'Alt' key is active, or false if it is inactive ctrlKey - indicates true if the 'Ctrl' key is active, or false if it is inactive. shiftKey - indicates true if the 'Shift' is active, or false if it is inactive.

- The code values for "charCode" and "keyCode" are dependent on the operating system and keyboard being used. The examples here are for Windows. - To detect in a Flash presentation which key is pressed, apply the addEventListener() method (with KeyboardEvent) to Stage (to the stage object). Here's an example with "KeyboardEvent" and KEY_DOWN, in which the "keyCode" property is used. We create a Flash presentation with a rectangle (or what shape you want) that can be moved with the arrow keys. Also, it uses the "shiftKey" property to modify the motion speed when the Shift key is pressed. - Follow this steps: 1. Open a new Flash document, ActionScript 3.0, and draw a rectangle (or what shape you want) on the Stage. 2. Select the shape on the Stage and convert it into MovieClip (from Modify -> Convert to Symbol, and for Type choose Movie Clip, and press OK). Then, open the Properties panel, and add the instance name rectangle for this MovieClip object (in the box with "<Instance Name>"). 3. Right-click on Frame 1 in the Timeline, choose Actions, then in the "Actions panel" add the following code:
4. // Register a KeyboardEvent, applied to the "stage" object, to detect when a key is pressed 5. // addEventListener is applied to the 'stage' object, to be active in all the presentation 6. stage.addEventListener(KeyboardEvent.KEY_DOWN, moveF); 7. 8. // Function called by the registered event 9. function moveF(key_evt:KeyboardEvent):void 10. { 11. // define a variable with a value that depends on "shiftKey" (used to set the motion speed) 12. var vi:int = key_evt.shiftKey ? 12 : 2; 13. 14. // define a "switch" instruction with values and instructions for arrow keys 15. // uses the code valuess for the arrow keys: Left, Right, Down, Up 16. switch (key_evt.keyCode) 17. { 18. case 37: 19. rectangle.x -= vi; 20. break;

21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. }

case 39: rectangle.x += vi; break; case 38: rectangle.y -= vi; break; case 40: rectangle.y += vi; break; default: break; }

34. Press Ctrl+Enter to test the result. The following Flash presentation will appear: - When you press the arrows keys, the rectangle will move in the direction indicated by each arrow (first click on the presentation). - If you hold the Shift key pressed, the motion speed will increase. - The expression "var vi:int = key_evt.shiftKey ? 12 : 2;" defines the value of 12 if "key_evt.shiftKey" is TRUE (when Shift is pressed) or 2 if it's FALSE (Shift is not pressed). - The "switch" instruction modifies the 'x' and 'y' values for the "rectangle" instance (X and Y distance), with the value of the "vi" variable, depending on the arrow key you press (a "case" for each arrow key). To find out the code for each key, you can use the following ActionScript code:
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyC); function keyC(key:KeyboardEvent):void { trace(key.keyCode); } // Displays in the Output panel the code value of the key pressed

To download the FLA file with this example, click: Keyboard events.

Adding Text with Action Script 3


In this lesson we will explain methods to create and add text in a Flash presentation using ActionScript 3.0, as well as a few properties and methods used to define text. - Why create Text or other objects with ActionScript when they can be created directly on the stage? Because you can personalise the text added with ActionScript, and display the text you want dinamically, according on certain actions. To create text with AS3 you use the TextField class, this class contains many properties and methods to define text; such as, color, size, position and others. Here are a few properties that can be applied directly to the instance for text.

x - Sets the text fields distance from the left edge y - Sets the text fields distance from the top edge width - Defines the lenght of the text field height - Defines the height of the text field textColor - The text color (defined in 0xRRGGBB, RGB = Red, Green, Blue) backgroundColor - Defines the background color of the text area background - true or false, specifies if the defined background will be displayed borderColor - Defines a color for the border around the text border - true or false, specifies if the defined border will be displayed autoSize - Controls automatic sizing and alignment of text fields. The values that it can receive are: "none", "left", "right" and "center". text - Adds the text in the "textField" instance htmlText - Adds a HTML formatted text. The following tags are recognized: <a> (with the attributes: "href" and "tatget"), <b>, <br>, <font>, <img> (JPG, GIF, PNG, SWF. It uses a "id" in which, the MovieClip instance's name that contains the image is specified, <i>, <li> (without <ul> or <ol>), <p>, <span>, <u>; and also the HTML entities: &lt;, &gt;, &amp;, &quot;, &apos; styleSheet - Attaches an instance to the text with CSS styles, created with the "StyleSheet" class multiline - true or false, indicates whether field is a multiline text field wordWrap - true or false, indicates whether the text field has word wrap.

- The complete list with ActionScript 3 properties and methods can be found at the official Adobe Flash webpage: TextField properties and methods. - First create a variable with a "TextField" instance, then, you can add the text and define properties to the instance. To add the text in a presentation, use addChild(). In the next example you can see how to create a text and define some properties: 1. Open a new Flash document, ActionScript 3.0 2. Right-click on the first frame in the Timeline and choose Actions

3. Add the following code n the "Actions panel":


4. // Initialize a "TextField" instance 5. var txt:TextField = new TextField(); 6. 7. // set properties to define the text field 8. txt.x = 50; // Distance from the left edge 9. txt.y = 80; // Distance from the top edge 10. txt.width = 200; // Lenght of the text field 11. txt.textColor = 0x0000da; // Text color 12. txt.backgroundColor = 0xededfe; // Sets the background color 13. txt.background = true; // Enables to display the background colors 14. txt.borderColor = 0x007800; // Sets the border color 15. txt.border = true; // Enables to display the border 16. txt.text = "Welcome to CoursesWeb.net \n Farewell"; // Adds text 17. 18. // Align the text in the created field 19. txt.autoSize = "center"; 20. 21. // Apply "addChild()" to add the text in the Flash presentation 22. addChild(txt);

- "\n" adds a new line. - When the "autoSize" property has the "none" value, the text area and the text field are the same, but when it is given a different value (left, right, center) the text area (background and border) will only encompass the area occupied by the text. 23. To see the result, press "Ctrl+Enter", it will appear like in the following image:

The FLA file with this example can be downloaded from: Text with AS3. In the text added with ActionScript you can use some HTML tags and CSS. - To add text which contains HTML tags, you must use the "htmlText" property. Only a few HTML tags are recognized, the ones presented above at this property. - To add CSS styles, you must use the "styleSheet" property, the "StyleSheet" object and it's method,

"parseCSS("stilCSS")", which takes as argument a row with CSS properties. You can find the list with the "StyleSheet" at the following webpage: StyleSheet methods and properties The CSS properties that are recognized are: color, display, font-family, font-size, font-style, font-weight, leading, letter-spacing, margin-left, margin-right, text-align, text-decoration, text-indent. Let's see an example with text formated with HTML tags and CSS styles (explanations are in the code).
// Initialize a "TextField" instance var txt:TextField = new TextField(); // Defining properties for the text field txt.width = 180; txt.height = 100; txt.wordWrap = true; txt.multiline = true; // store CSS styles in a String variable var css_st:String = ".bv{color:#0808fe; font-family:Arial; font-size:16px; font-weight:bold;} .adf{color:#ed0708; font-family:Verdana; font-size:13px; font-style:italic}"; // Defines the instance for the "StyleSheet" object var styles:StyleSheet = new StyleSheet(); // Applies the "parseCSS" method to the variable with the CSS styles styles.parseCSS(css_st); // uses the "styleSheet" property to attach the CSS styles to the "txt" instance txt.styleSheet = styles; // Adds HTML formated text txt.htmlText = '<span class="bv">Welcome</span><br><font size="12" color="#00a800">to <u><a href="http://coursesweb.net">coursesweb.net</a></u></font><br><span class="adf">ActionScript course</span>.'; // add the text in the Flash presentation addChild(txt);

- This code will show a Flash presentation like in this image:

To download the FLA file with this example, click Text with HTML and CSS. Using TextFormat

The TextFormat object gives another way to format and define a text in a "textField" instance. To use TextFormat, you must create an object with new TextFormat(). This object has specific properties and methods to format text, these are presented on this page: TextFormat properties and methods The instance of the TextFormat must be added to the object which contains the text (created with "textField").
- Here's an example with "TextFormat":
// Create a TextFormat instance var textF:TextFormat = new TextFormat(); // sets properties to format the text textF.leftMargin = 55; // the left margin of the paragraph, in pixels textF.font = "Arial"; // Defines the font used textF.color = 0x5678fe; // Color textF.size = 17; // Text size (in pixels) // Initialize a "TextField" instance in a "txt" variable var txt:TextField = new TextField(); // Defining properties for the text field txt.width = 240; txt.wordWrap = true; txt.multiline = true; txt.text = "Text with TextFormat \nActionScript 3 Course"; Text // Adds the

// Apply "setTextFormat()" to the text field , with the "textFormat" instance as argument

txt.setTextFormat(textF); // add the text in the Flash presentation addChild(txt);

- This code will display a Flash presentation like in this image:

To download the FLA file with this example, click Text and TextFormat. You can also apply TextFormat to a portion of text only, with the following method:
txtField.setTextFormat(textFormat, beginIndex, endIndex);

- "txtField" is the instance created with "TextField" - "textFormat" is the instance created with "TextFormat" - "beginIndex" is an integer that specifies the first character of the desired range of text - "endIndex" is an integer that specifies the character after the desired text span. For example, try using txt.setTextFormat(textF, 5, 15); to the previous script.

Characters used for text in a TextField instance can be restricted with REGEX expresions, using the property restrict. Exemple: textField.restrict = "0-9"; // Allows only numbers textField.restrict = "0-9 A-F"; // Allows only numbers and capital letters from A to F textField.restrict = "0-9 A-F ^ a-z"; // Allows numbers and capital letters from A to F, without small letters

Another method to create text fields in flash, in which the text is interactively added with ActionScript, is combining text field made on the stage (with "Text tool") and the AS3 code. The method is simple, make a field for text on the stage (with "Text Tool"), and add an instance name for this field (in Properties panel), then the instance name can be used in ActionScript code as if it was a "TextField" instance. The advantage is that multiple graphical options can be combined and applied to the text with instruments from the stage and the interactivity given by ActionScript.

Input Text Field


Input text fields are zones in which the user can add and modify text. To create an input text field, define a TextField object, then set the value "input" (or TextFieldType.INPUT) for its "type" property.
- Syntax:
var inputField:TextField = new TextField(); inputField = "input";

Once you have created an object for Input Text Field (with the "TextField" class), you can access various properties of this object to define the text area, the size, position, text format, and other properties for the input field. Such as, defining a border, background color, setting the allowed number of characters or restricting the characters that can be added in the input field. Here's an example with Text Input (See the explanations in the code):
// Defining a TextField object instance var txt_inp:TextField = new TextField(); // Apply properties to "txt_inp" instance txt_inp.type = "input"; // Set the text field as Input txt_inp.x = 100; // Distance from the left border txt_inp.y = 50; // Distance from the top border txt_inp.width = 100; // Length of the text field txt_inp.height = 20; // Height txt_inp.border = true; // Enable to display border txt_inp.borderColor = 0x0000da; // Define the border color // define to allow only numbers and small letters from 'a' to 'e'

txt_inp.restrict = "0-9 a-e"; // Set the maximum number of characters that can be written txt_inp.maxChars = 28; txt_inp.text = 'Name'; // The initial text in the input field

// Add the "txt_inp" instance in the Flash presentation addChild(txt_inp);

- This code will display the following Flash presentation. You can delete and add another text in the input field, but, becouse the "restrict" property is set ( txt_inp.restrict = "0-9 a-e"; ), you can only write numbers and letters from 'a' to 'e'. To download the FLA file with this example, click Input TextField. - To be able to add multiple rows of text (with enter) in the Input field, you must set the multiline property to true (txt_inp.multiline = true;). - To make the Input Text an Input field for password (the characters to be hidden and displayed with asterisk "*"), set the displayAsPassword property to true. - To format the text in the Text field, apply the properties of the "TextFormat" object. Using TextEvent Input

Usually, the text added in an Input field is used for certain actions. With the "addEventListener()" and TextEvent.TEXT_INPUT event applied to a TextField instance, the Flash detects the time (or event) when the user writes something in the Input field; it can take the character or text added in the field, and perform different instructions according to the text added. The syntax to use the "TextEvent" object is:
inputField.addEventListener(TextEvent.TEXT_INPUT, someFunction); function someFunction(insTxtEv:TextEvent):void { // code to be execute, when the user adds a character in "inputField" }

- "inputField" is the "TextField" instance for the Input text field. - "addEventListener()" is an ActionScript 3 method used to detect events in the Flash presentation. - "TextEvent.TEXT_INPUT" sets the event type that must be detected. - "someFunction" is the function that will be called when the user writes in the Input field. - "insTxtEv" receives data passed by the event listener. - insTxtEv.text returns the last character inserted by the user in the Input field.

The TEXT_INPUT event is not dispached when the user delete the text (with Delete or Backspace)

Here's an example. We create an input text field and define an event listener to change the border and background color of the input field, depending on the number of characters added in that text field.
// Define a TextField instance var txt_inp:TextField = new TextField(); // Apply properties to the "txt_inp" instance txt_inp.type = "input"; // Sets the text field as Input txt_inp.x = 100; // Distance from the left border txt_inp.y = 50; // Distance from the top border txt_inp.width = 100; // Length of the text field txt_inp.height = 20; // Height txt_inp.border = true; // enables to display the border txt_inp.borderColor = 0x0000da; // Define the border color txt_inp.maxChars = 28; // Maximum number of characters allowed txt_inp.backgroundColor = 0xfefe18; // Define the background color txt_inp.background = true; // enable to display the background // Add the instance with "txt_inp" in the Flash presentation addChild(txt_inp); // Register an event listener that detects when something is written in the TextField txt_inp.addEventListener(TextEvent.TEXT_INPUT, txtInp); // The function that will be called by the event listener function txtInp(txtEvent:TextEvent):void { // gets the number of characters (stored in "txt_inp") var nr:int = txt_inp.text.length; // depending on the number of characters, changes the border and background color if(nr<3) txt_inp.borderColor = 0xda0000; else if(nr<5) txt_inp.borderColor = 0x00da00; else if(nr>5) txt_inp.backgroundColor = 0xfea8fe; }

- If you add this code in a new Flash document, the result will be the following presentation. To see the effect, type a few characters in the text field. To download the FLA file with this example, click TextEvent Input. - To capture the character typed by the user, but to not add it in the input field, use the preventDefault() method in the function called by the event listener (for example, txtEvent.preventDefault();). It is useful when, for example, you want to display a different word or character depending on what it is written. - To add multiple input text fields, you must create a "TextField" instance for each Input field. FocusEvent - FOCUS_IN and FOCUS_OUT events FocusEvent object can be used to detect when the user changes the focus from a text field. - FocusEvent.FOCUS_IN - is dispatched when the TextField receives focus from the user. - FocusEvent.FOCUS_OUT - is dispatched after the TextField loses focus.

Study the next example. It creates two input text fields, and registers FOCUS_IN and FOCUS_OUT events to change the border and background color when the user changes the focus from these text fields.
// Function to create Input Text fields // Takes as argument: a TextField instance, Y distance and the initial text function setInput(inst:TextField, dy, txt):void { // Apply properties to the instance in the "inst" parameter inst.type = "input"; // Set the text field as Input inst.x = 100; // Distance from the left border inst.y = dy; // Distance from the top border inst.width = 100; // Length of the text field inst.height = 20; // Height inst.border = true; // enable to display the border inst.borderColor = 0x0000da; // Define the border color inst.maxChars = 28; // Maximum number of character allowed inst.backgroundColor = 0xe8e8e8; // Define the background color inst.background = true; // enable to display the background inst.text = txt; // adds the initial text in the Input // Add the instance in the Flash presentation addChild(inst); } // Function for FOCUS_IN function setFIn(focus:FocusEvent):void { // Define the border and background color for the target field (focus.target as TextField).borderColor = 0x00d800; (focus.target as TextField).backgroundColor = 0xfefe08; } // Function for FOCUS_OUT function setFOut(focus:FocusEvent):void { // Define the border and background color for the target field (focus.target as TextField).borderColor = 0xfe0000; (focus.target as TextField).backgroundColor = 0xe7e8fe; } // Define the first and second TextField instance var txt_inp1:TextField = new TextField(); var txt_inp2:TextField = new TextField(); // register FocusEvent listener (FOCUS_IN and FOCUS_OUT), for each instance txt_inp1.addEventListener(FocusEvent.FOCUS_IN, setFIn); txt_inp1.addEventListener(FocusEvent.FOCUS_OUT, setFOut); txt_inp2.addEventListener(FocusEvent.FOCUS_IN, setFIn); txt_inp2.addEventListener(FocusEvent.FOCUS_OUT, setFOut); // Call the function "setInput" to define the fields for each TextField instance setInput(txt_inp1, 50, 'Input 1'); setInput(txt_inp2, 80, 'Input 2');

- The Flash presentation displays 2 Text Input fields. When the user clicks on any of them, its background and border colors change (as set in the "setFIn()" function), and when that field loses focus, the border and background color change again (as set in the "setFOut()" function). To see the effect, click on each text field. To download the FLA file with this example, click FocusEvent - FOCUS_IN and FOCUS_OUT.

addChild and removeChild


addChild() and removeChild() are methods which add and remove visual elements on the stage.

addChild
addChild is an ActionScript function that adds visual elements in the Flash presentation. It's general syntax is:
addChild(displayObject);

- "displayObject" is the object that must be displayed in the Flash presentation (such as: a text field, a geometric figure, an image, etc.). You can see in the next example how to apply it. The script in this example displays three text fields, with text that is taken from an Array, and background color for each field, defined in a different Array. Also see the explanations from code.
var texts:Array = ['courses', 'tutorials', 'coursesweb.net']; // Array with texts to display var bcolor:Array = [0xe8e9fe, 0xeded01, 0xfedada]; // Array with colors for the background of each text var lung:int = 110; // Variable used for the lenght of the text field // Read through the "texts" Array for(var i:int=0; i<texts.length; i++) { // creates a field "TextField" for each element in texts // Sets the fields height, lenght, and distance "x" depending on "i" (for liniar display)

// Adds background color from "bcolor" Array and text from the current element in "texts" var txt:TextField = new TextField(); txt.height = 25; txt.width = lung; txt.x = i*(lung + 8); txt.backgroundColor = bcolor[i]; txt.background = true; txt.text = texts[i]; addChild(txt); } // Add the field in the scene.

- The code "for(var i:int=0; i<texts.length; i++)" reads the "texts" Array and for each current element it creates a Text Field object, and "addChild(txt);" adds this "txt" object on the stage , with all it's settings (size, background color, text, etc.). - It will display a row with 3 text areas in the Flash presentation, like this: courses tutorials coursesweb.net The FLA file with this example can be downloaded from: AS3 addChild.

removeChild
removeChild is an ActionScript function that deletes visual elements from the Flash presentation. It's general syntax is:
removeChild(removeObject);

- "removeObject" is the object that must be deleted from the flash presentation (such as: a text field, a geometric figure, an image). When the same instance is added multiple times (as in the example above, the "for()" loop creates and adds the same "txt" instance 3 times), the last one is retained in memory as being that objects instance. In this case using the "removeChild(insObj)" method will delete the last element with the instance name "insObj", even if more were added, the others do not exist with that name. You can see in the following example how to apply the "removeChild()", and the effect obtained. 1. Open a new Flash document and draw a geometric figure (square, circle) on the stage and turn it into a button (from the Modify -> Convert to Symbol). 2. Give the button the name "remove_bt" (in the Properties panel, at "<Instance Name>"). 3. Right-click on frame 1 in the Timeline, choose "Actions", and in the Actions panel add the following code:
4. var texts:Array = ['courses', 'tutorials', 'www.marplo.net']; // Array with text to display. 5. var bcolor:Array = [0xe8e9fe, 0xeded01, 0xfedada]; // Array with colors for the background of each text 6. var lung:int = 100; // Variable used for the lenght of the text field 7. 8. // Reads through the "texts" Array 9. for(var i:int=0; i<texts.length; i++) 10. {

11. 12.

// creates a field "TextField" for each element in texts // Sets the fields height, lenght, and distance "x" depending on "i" (for liniar display) 13. // Adds background color from "bcolor" Array and text from the current element in "texts" 14. var txt:TextField = new TextField(); 15. txt.height = 25; 16. txt.width = lung; 17. txt.x = i*(lung + 8); 18. txt.backgroundColor = bcolor[i]; 19. txt.background = true; 20. txt.text = texts[i]; 21. 22. addChild(txt); // Adds the field on the stage 23. } 24. 25. // Recording CLICK event for the button on the stage, "remove_bt" 26. remove_bt.addEventListener(MouseEvent.CLICK, removeIns); 27. 28. // The function called by the registered event 29. function removeIns(evt:MouseEvent):void 30. { 31. removeChild(txt); // Delete's the element with the instance "txt" 32. }

- This script adds three text fields (as in the previous example) in the flash presentation, above the button from the stage. When the button is pressed, this activates the "MouseEvent.CLICK" event that calls the "removeIns()" function. - The "removeChild(txt);" command deletes the "txt" object instance. 33. If you press "Ctrl+Enter", the result will be like in the following presentation. - As the same instance is added multiple times, the last one rewrites from memory the previous one. The button will delete the last text field added, but it will not recognize the others as being the "txt" instance and if the button is pressed again it will give an error. To download the FLA file with this example, click: AS3 removeChild. removeChildAt

When elements are added with "addChild", they are retained in memory, in an Array in the adding order, starting the indexing from the number of those added on the stage. For example, if on the stage there's only a button , it has the index 0 and the following are indexed as numbered after it (1, 2, ...). The "removeChildAt()" method can delete elements in a Flash presentation, according to their index:
removeChildAt(index)

- When an element is deleted, the index order in the Array from memory is updated, so, the element that is recorded after the deleted one will take it's index, the following one decreases with a unit, and so on. You can understand it better from the following example witch is a new version of the previous one. Leave the button "remove_bt" on the stage (from the document created for the previous example), delete the code in the Actions panel and add this one:
var texts:Array = ['courses', 'tutorials', 'www.marplo.net']; // Array with text to display var bcolor:Array = [0xe8e9fe, 0xeded01, 0xfedada]; // Array with colors for the background of each text var lung:int = 100; // Variable used for the lenght of the text field // Reads through the "texts" Array for(var i:int=0; i<texts.length; i++) { // creates a field "TextField" for each element in texts // Sets the fields height, lenght, and distance "x" depending on "i" (for liniar display) // Adds background color from "bcolor" Array and text from the current element in "texts" var txt:TextField = new TextField(); txt.height = 25; txt.width = lung; txt.x = i*(lung + 8); txt.backgroundColor = bcolor[i]; txt.background = true; txt.text = texts[i]; addChild(txt); } // Recording CLICK event for the button on the stage, "remove_bt" remove_bt.addEventListener(MouseEvent.CLICK, removeIns); // The function called by the registered event function removeIns(evt:MouseEvent):void { removeChildAt(2); // Deletes the element with index 2 } // Adds the field on the stage

- When the button is pressed, the comand "removeChildAt(2);" deletes the element with index 2. Two text fields remain on the stage (the first and the third, but the memory index gets updated, so, the field that had the index 3 will get index 2, fact demonstrated if the deletion button is pressed again. According to the code, it will always delete the element with the index 2. When on the stage the are no more elements that can take the place of the one deleted, pressing the button will give an error. The FLA file with this example can be downloaded from: AS3 removeChildAt. getChildByName

Besides the numerical index of the elements, they are also recorded with an unique name, that will not change when an element is deleted.

Each element added in the flash presentation has a unique name. If the name of the element is not specified, will be automaticaly added by the program with the name "instanceNR" ('NR' is the serial number: "instance12", "instance13", ...). This name can be defined with the property name, with the following syntax:
insObj.name

- "insObj" is the instance of the element added in the Flash presentation. - This command sets, but also returns, the name of that instance, for example: trace(insObj.name); If you set a name, you'll have a more efficient control over the objects. To access an object by its name, use the following function:
getChildByName("name")

- "name" is the name defined with "insObj.name". Here's how you can apply "insObj.name" and "getChildByName()" to the previous example. Use the same flash document (with the "remove_bt" button), and add the following ActionScript code (any existing code must be deleted).
var texts:Array = ['courses', 'tutorials', 'www.marplo.net']; // Array with text to display var bcolor:Array = [0xe8e9fe, 0xeded01, 0xfedada]; // Array with colors for the background of each text var lung:int = 100; // Variable used for the lenght of the text field // Reads through the "texts" Array for(var i:int=0; i<texts.length; i++) { // creates a field "TextField" for each element in texts // Sets the fields height, lenght, and distance "x" depending on "i" (for liniar display) // Adds background color from "bcolor" Array and text from the current element in "texts" var txt:TextField = new TextField(); txt.height = 25; txt.width = lung; txt.x = i*(lung + 8); txt.backgroundColor = bcolor[i]; txt.background = true; txt.text = texts[i]; // Atributin a name to the instance, for it to be unique also use 'i's value txt.name = 'camp'+i; addChild(txt); } // Recording CLICK event for the button on the stage, "remove_bt" remove_bt.addEventListener(MouseEvent.CLICK, removeIns); // Adds the field on the stage

// The function called by the registered event function removeIns(evt:MouseEvent):void { removeChild(getChildByName('camp0')); // Deletes the element with 'camp0' name removeChild(getChildByName('camp1')); // Deletes the element with 'camp1' name }

- the "txt.name = 'camp'+i;" expression within the "for()" loop gives each "txt" instance a registration name: camp0, camp1, camp2. - By knowing the added names, the "getChildByName()" method can be used. Observe the command "removeChild(getChildByName('camp0'));", "removeChild()" deletes the element taken by "getChildByName()". The result of this example will be the one from the following presentation - Once the text fields with the name: "camp0" and "camp1" are deleted, no other element with those names will exist in the presentation. To download the FLA file with this example, click: AS3 getChildByName &bull Other useful functions from this category:

addChildAt(insObj, nr) - adds an "insObj" object instance with the 'nr' index getChildIndex(insObj) - returns the index of a "insObj" object instance setChildIndex(insObj, nr) - changes the index (and position) of an instance with the one given at 'nr' swapChildren(insObj1, insObj2) - switches "insObj1" position with "insObj2" position swapChildrenAt(index1, index2) - swaps the z-order (front-to-back order) of the child objects at the two specified index positions in the child list.

OOP Class and Object Create Class


OOP (Object Oriented Programming) is a programming concept (or technique), which treats data and functions as objects. Important to this concept is to understand the difference between a Class and an Object.

- A class is a "blueprint" for an object, is a code template used to generate objects. It contins the instructions that define the properties and methods that an object can use. - Objects are elements from the script that are defined to perform the instructions written in a class, and can use the properties and methods defined in the class. - For example, to understand, you can think of a class as a blueprint for constructing an house. Many houses can be built from the same blueprint, so, the object is the house created according to that blueprint. You can build multiple objects that have the properties defined in the class. The difference between Class and Object is important. If a class can be asimilated to a type of data, an object can be equated with a variable or with a value having a certain type of data. Practically, a class is a "factory" of objects, that produces objects with the same structure, having the same properties and methods.

An object is also called a class instance. In OOP (Object Oriented Programming) we encounter terms like "Encapsulation" and "Polymorphism". - Encapsulation represent the fact that you can use a class (its properties) through an object instance, without having access to its code. - Polymorphism is a class ability to do more different things, or use one class or another to achieve the same thing, having similar functions. (For example, you can drink water using a glass, a cup or a bottle. That is Polymorphism).

Defining a class
ActionScript 3 contains several predefined classes, such as "Date class" used when working with date and time, "String class" for strings, and others; but you can also create your own classes. To create a class use the class keyword, followed by it's name and it's body (contained between curly brackets). The properties and methods are defined in the class body. - Properties are variables defined within the class. - Methods are functions created within the class. The general structure of a class is:
class ClassName { var property1; var property2; ................. function method1() { // Funtion code } function method2() { // Function Code } ................. }

To build a working class that can be used in the Flash document, it is necessary to add other things too.

- First of all, each class must be created inside a Package. The Package is a structure through which multiple classes can be grouped together. This helps to create different classes that can have the same name. - When you create a class, you can specify special attributes for properties and methods to define their level of access. This attribute is added before the defining word (class, var, const and function), and can be one of the following keywords:

public - available in all script private - available only inside the same class protected - available in that class and its sub-classes internal - available in the classes of the same package

- If no attribute is added, it is considered "private". So, the complete syntax to create a class is:
package packageName { attribute class ClassName { attribute var property1; attribute var property2; ................. attribute function method1() { // Function code } attribute function method2() { // Function code } ................. } }

- "packageName" is optional, for beginners it's better to not specify it, because needs extra things (explained below). The class is NOT written inside the FLA document, it is created in an external file, with the "as" extension. From the menu New choose "ActionScript 3.0 Class" or "ActionScript File". Flash opens a small window to add the name of the class, then Flash opens a new a document, where you can write the class code. In this document, the "package", the class body, and the constructor method are already written. You can delete them or complete them with your code. Here's an example of a simple class, it contains a property (named "prop"), a method (with the name "metod"), both with "public" attribute, so they can be accessed outside the classe (in a script) and a constant named HIDEN, (with "protected" attribute), so that it can only be used inside the class and it's sub-classes.

TestClas Example
// create the package package {

// define the class, with public attribute, a property "prop" and a method "metod" public class TestClas { public var prop:Number = 7; // Public property protected const HIDEN:int = 2; // "Protected" constant // Creating the method, takes an argument (Number type) public function metod(val:Number):void { // changes the value of the "prop" property, with the "val" parameter and the "HIDEN" constant this.prop = val + HIDEN; } } }

- "this.prop" indicates the property "prop" from this class (the term this is added to indicate that it refers to the property of the current class, avoiding errors that can appear if in that function you use other parameters and variables with the same name). - After you defined the code of the class, you must save this document with the same name as the class (e.g., "TestClas.as"), from File -> Save, in the same directory in which you have the FLA document which will use this class (if "package" is without a name). Note, multiple classes can not be created in the same "package" body. This actually represents a folder where the "AS" files with classes that belong to the same group are added. In the "package body" (between it's curly braces) only one class can be created. - The question is, how can a "package" contains multiple classes? Package actually represents the path and folder where "AS" files with classes included in that package are saved, each file contains only one class, and all of them form the group inside the package. The folder and the package must have the same name; so the classes that are saved in a directory belong to the "package" with the same name. - For example, if you want to group two classes (Class1 and Class2) in a package named "group", create a folder "group" (in the same place where the FLA document is saved) and in this folder save the two "AS" files with the code of the classes ("Class1.as", and "Class2.as"). These classes are grouped in the "group" package and can be used in the script with the expression "group.Class1", respectively "group.Class2". To use a class or a group of classes from a package, these must be imported in the document, with the syntax:
import packageName.ClassName;

OR:
import packageName.*

- The first formula imports only the "ClassName" class from the "packageName" package, the second formula imports all the classes from that package (folder). Classes defined in a simple package (without name) and that are saved in the same directory with the Flash document, it's not necessary for them to be imported.

Using a Class

Once a class is created and saved in a file "ClassName.as", you must create an object instance of that class to can use its properties and methods in a script. This instance must be declared in the script written in the FLA document as any other object used in ActionScript 3 (such as Array, Date, etc., these are also classes), with the sintax:
var name_ins:ClassName = new ClassName();

OR:
var name_ins:packageName.ClassName = new packageName.ClassName();

(if the class is in a package with a name) - "name_ins" is the name of the instance (or object) through which the classe's properties and methods can be used. Here's an example how the "TestClas" presented above can be used. Copy the code from "TestClas example" in a document "ActionScript 3.0 Class" and save it with the name "TestClas.as" in the same folder as the FLA document which will use this class. In the Flash document add the following AS3 code:
// Creates the object instance of the TestClas class var tst:TestClas = new TestClas(); // Checks the value of the "prop" property trace(tst.prop); // 7 // access the "metod()" method, which change the value of "prop" tst.metod(18); // checks "prop" trace(tst.prop); // 20

- Because the FLA file and the TestClas class are in the same folder, Flash automatically imports this Class when an instance is created. When you access the properties and methods (through the instance), the instructions asociated to them in that class are executed in the script. - The constant "HIDEN" having the attribute "protected", can be used only in the class code (or it's subclasses), if you try to access it outside the class (e.g., trace(tst.HIDEN)), an error will be returned. The constructor

The constructor is a special function inside the class. It must have the same name as the class. This method is always "public" even if this attribute is not mentioned. The constructor is automatically called when an instance of the respective class is created. Another difference from other functions is that the Constructor not use the "return" instruction.

Here's a new version of the "TestClas" class, that includes the contructor method.
// create the package

package { // define the class, with public attribute public class TestClas { public var prop:Number = 7; // Public property protected const HIDEN:int = 2; // "protected" constant // Creating the constructor public function TestClas(nr1:Number, nr2:Number) { // stores in a variable the arithmetic average of the "nr1" and "nr2" parameters var average_a = (nr1+nr2)/2; trace(average_a); // Returns in output the "average_a" value } // Create method (takes a Number type argument) public function metod(val:Number):void { // change the value of the "prop" property, a number given by the "val" parameter and the "HIDEN" constant this.prop = val + HIDEN; } } }

- Notice that the contructor method has the same name as the class. The constructor is defined with two parameters ("nr1" and "nr2"), when an instance of this class is created, two values must be added as arguments (new TextClass(val1, val2)). Save this class and write the following code in the Actions panel:
var tst:TestClas = new TestClas(7, 8);

- In the Output panel will be displayed the number 7.5, fact that demonstrates that the Constructor method is called automatically and its code is executed when an object instance is created. The Accessor method

The variables (or properties) created in a class can be defined with a value or they can simply be declared without value. Then you can create a function to change or assign their value. This function is generically called Accessor method, it's the same as any other method, only that it's purpose is to attribue values to properties. To see how the "accessor method" works, try the following example, in which a class "testclas2" is created with two properties (without value), and an accessor function that assigns value to these properties. - Open a new document with "ActionScript 3.0 Class", give it the name "testClas2". Delete the initial code and copy the following code, then save the file, with the name "testClas2.as", in the same folder as the FLA document is.
package { // define the class public class testClas2 { // Defining properties without value public var prop1:Number;

public var prop2:String; // Create accessor method public function setProp(prop1:Number, prop2:String) { // Assign values to the properties (the ones with "this") this.prop1 = prop1; this.prop2 = prop2; } } }

- The function's parameters (in this case "setClas(prop1, prop2)") can have any name, but setting their name as the properties they represent helps you later to know their role and easier to understand the code. - The "this" instruction specifies exactly which the property is, and makes the difference between property and parameter with the same name. in the ActionScript panel from the Flash document (saved in the same folder as "testClas2") add the following code:
// Create object instance of the testClas2 class var obj4:testClas2 = new testClas2(); // Verify in Output 'prop1' and 'prop2' trace(obj4.prop1+"-"+obj4.prop2); // NaN-null // Call the accessor method obj4.setProp(8, 'Tutorials'); // Verify 'prop1' and 'prop2' again trace(obj4.prop1+"-"+obj4.prop2); // 8-Tutorials

- "NaN" is returned by a Number type variable without value, "null" by a String type variable without value. - After calling the method "obj4.setProp(8, 'Tutorials');", "prop1" and "prop2" receive the arguments value, 8 and 'Tutorials'.

This method is usefull when you want the properties value to be dinamically defined in the script.

- The FLA and AS files with the examples from this lesson can be downloaded from: OOP - Classes and objects - Create Class.

Classes Static Element


In a class in ActionScript you can also create static elements (variable, methods, constante). Static elements belong exclusively to a class, and can not be accessed through an instance of the class, but directly using the name of the class. To create static elements, you use the keyword static in the definition of the element.
Static properties

Variables defined in a class are associated with properties that can be accessed through an instance of that class (if they have the "public" attribute), with this syntax: instance_name.property

Variables, or static properties are created by adding the keyword static before keyword var in the variable definition:
attribute static var prop_name:DataType = value;

Static properties belong to the class and can be accessed with this syntax:
ClassName.prop_name

Here's an example. We create a class (named "elStatic") with two public properties, the second property is defined as static. - If you do not know how to create a class in AS3 and use it in Flash, first study the lesson: OOP - Classes and objects - Create Class
package { // Define "elStatic" class public class elStatic { // Define properties public var prop1:String = 'coursesweb.net'; public static var prop2:String = 'ActionScript'; variable } }

// Static

- Open a new Flash document, in "Actions panel" add the following code, then save this document in the same folder as the file with this class, "elStatic.as".
// Create an instance of the "elStatic" class var obj:elStatic = new elStatic(); // access the class property trace(obj.prop1); // coursesweb.net // trace(obj.prop2); // Will generate an error // acces 'prop2' directly through the class name trace(elStatic.prop2); // ActionScript

- Press "Ctrl+Enter to see the result in Output. - If you delete the backslashes (//) in front of the expression "trace(obj.prop2);", it will generate an error. "prop2" having the "static" attribute, is not recognized in the instance of the class ("obj"), but can

be accessed directly through the class name (elStatic.prop2). To access a static variable inside the class code, you can use its name, or the expression "ClassName.static_prop". Static constants

Constants are variables with a fixed value, they are defined with the instruction const, and their value can not be changed. Static constants are created by adding the keyword static before keyword const. - To access a static constant, use the expression:
ClassName.CONSTANT

- Inside the class, static constants can be accessed directly with their name or with the syntax above. In the following example (continuing the one above) we add 2 constants, both with "public" attribute. The second constant is defined as static.
package { // Defining "elStatic" class public class elStatic { // Defining the properties public var prop1:String = 'coursesweb.net'; public static var prop2:String = 'ActionScript'; variable // Defining constants public const TUTORIALS:String = 'web development'; public static const SITE:String = 'coursesweb'; constant } }

// Static

// Static

- In the Flash document add the following code:


// Create instance of the class "elStatic" var obj2:elStatic = new elStatic(); // access the class constants trace(obj2.TUTORIALS); // trace(obj2.SITE); // web development // Returns an error

// access 'SITE' using the class name trace(elStatic.SITE); // coursesweb

- If you delete the backslashes (//) in front of the expression "trace(obj2.SITE);", it will generate an error. The "SITE" constant, having the "static" attribute, is not recognized in the instance of the class ("obj2"), but can be accessed through the class name (elStatic.SITE). Static Methods

To create a static method, add the keyword static before the keyword function, in the method definition.

attribute static function methodName() { // code to execute }

To call a static method, use this syntax:


ClassName.methodName(parameters)

- In the body of a static method you can only use other static elements (properties, constants, methods). The keyword "this" can not be used. Let's continue the previous example, we add a static method (named "Courses") in the "elStatic" class, then we access it in a script (see the explanations in code).
package { // Defining the "elStatic" class public class elStatic { // Defining properties public var prop1:String = 'coursesweb.net'; public static var prop2:String = 'ActionScript'; variable // Defining constants public const TUTORIALS:String = 'web'; public static const SITE:String = 'coursesweb'; constant

// Static

// Static

// Defining a static method public static function Courses(param:String):String { var re:String; // The variable that will be returned // define "switch" instruction to set different posible values for "re" switch(param) { case 'web': re = elStatic.prop2; // "re" receives the value of the static property "prop2" break; case 'coursesweb': re = SITE; // "re" receives the value of the static constant "SITE" ( or elStatic.SITE; ) break; default: re = 'Default value'; } return re; } } } // Returns "re" value

- Because the "Courses" method is declared as static, can use only variables and constants that are also static. If, for example, you add in it's body "re = this.prop1;" or "re = TUTORIALS;" it will generate an error.

- In the Flash document add the following code:


var obj3:elStatic = new elStatic(); trace(elStatic.Courses(obj3.TUTORIALS)); // trace(obj3.Courses(elStatic.SITE)); // ActionScript // generate an error

// Call the static method, uses a static constant for argument trace(elStatic.Courses(elStatic.SITE)); // coursesweb

- if you delete the backslashes (//) in front of the expression "trace(obj3.Courses(elStatic.SITE));", it will generate an error. The method "Courses()" having the "static" attribute is not recognized in the instance of the class ("obj3"), but can be accessed with the class name (elStatic.Courses('argument')). To download the FLA and AS files with the examples of this lesson, click: Classes - Static Elements

Inheritance Parent Class and Child Class


nheritance is one of the most useful instruments of the Object Oriented Programming - OOP. Inheritage is a characteristic of the classes that lets you to transfer /use properties, constants and methods from one class to another, in an hierarchical structure. Inheritance enables you to define a base class (also called parent class) and create one or more classes derived from it. A class that inherits from another is said to be a subclass of it, or child class. A child class inherits all public and protected properties and methods from the parent, and can use them in it's own code and transmits them when an instance of the child subclass is created. As in nature, children inherit the parent's genes. Here's how to use inheritance in ActionScript 3 programming. We will create a base class, named "Mover", which can be used to move objects in a Flash presentation. The object that must be moved and the values for it's speed on the x/y axis are passed in arguments when the object instance of the class is created (more explanations are found in the code).
// Create the package (without name) package { // Import the predefined ActionScript 3 classes used in this class import flash.events.Event; import flash.display.MovieClip; // Start defining the Mover class public class Mover { // Setting properties // 'insMC' - for the MovieCplip instance, 'xVel' - for horizontal speed, 'yVel' - for vertical speed public var insMC:MovieClip; public var xVel:Number;

public var yVel:Number; // Create the constructor, takes as arguments a MovieClip instance and 2 numerical values function Mover(inMC:MovieClip, xV:Number, yV:Number) { // set the properties values with the values from parameters this.insMC = inMC; this.xVel = xV; this.yVel = yV; } // Create a method with "protected" attribute (can be used only in this class and it's sub-classes) protected function updatePosition(evtObj:Event):void { // Increments the 'x' and 'y' distance of the "insMC" with the values from the "xVel" and "yVel" properties this.insMC.x += this.xVel; this.insMC.y += this.yVel; } // Define a public method used to start the moving public function startMove():void { // Apply an event listener ENTER_FRAME to 'insMC' // this calls the protected method, updatePosition this.insMC.addEventListener(Event.ENTER_FRAME, this.updatePosition); } // Define a public method to stop the moving public function stopMove():void { // removes the event listener registered in "startMove()" insMC.removeEventListener(Event.ENTER_FRAME, this.updatePosition); } } }

- To test this class, follow these steps: 1. Open from File -> New a new "ActionScript 3.0 Class document". On the window that opens, type Mover for the class name. Delete the code that initially appears in the document and copy the code above, then save it with the name "Mover.as". 2. Open a new Flash document, draw a shape on the stage (for example a circle) and convert it into a MovieClip (from Modify - Convert to Symbol, make sure the middle point from Registration is checked, this sets its center of coordinates). Open the Properties panel and give the name "sfer" to the instance on the stage (the shape converted into a Movie Clip), in the top box, where "<Insance Name>" is written. 3. Right-Click on Frame 1 in the Timeline, choose Actions and add the following code in the Actions panel:
4. // Create an instance of Mover class 5. var obj:Mover = new Mover(sfer, 2, 3); 6. obj.startMove(); // Call the "startMove()" method

7. 8. // Call the "stopMove" method after 3 seconds (3000 milliseconds) 9. // "stopMove" deletes the record of the ENTER_FRAME event, and will stop the motion 10. setTimeout(obj.stopMove, 3000);

- "setTimeout()" is used to call a function /method after a specified time has passed (in milliseconds). 11. Save the Flash document in the same folder as "Mover.as", then press Ctr+Enter. The Flash Player will show a presentation like this (click on the image).

- This class moves the object in a single direction until it leaves the Stage (or until a "stopMove()" command is given), but maybe we want that some objects to move continuously inside the Stage area, bouncing from its border. Instead of creating a new class or modifying /ruining this one, we can define a child subclass that extends the "Mover" class. In the child class we import the parent class (Mover), then this child class will inherit the properties and methods used for motion. We only define the new instructions to change the motion direction when the object reaches the borders. To create a child class, you must use the extends keyword in the subclass declaration, followed by the name of the parent class:
package { import ParentClass; attribute class ChildClass extends ParentClass { // The code of the ChildClass } }

- When a class uses the properties and /or methods of another class, that class must be included (imported) with the import instructions. Here's how to create a child class (named "MoverChild") that extends the "Mover" class (defined above). Open another "ActionScript 3.0 Class" document, give it the class name MoverChild, delete its initial code and copy the following code:
// Create the package (without name) package {

// Import classes whose properties and methods will be accessed in this class import flash.display.MovieClip; import flash.events.Event; import Mover; // Import the parent class // Start defining the child subclass public class MoverChild extends Mover { // Constructor (receives 3 arguments, a MovieClip object and 2 numbers) public function MoverChild(inMC:MovieClip, xV:Number, yV:Number) { // Call the Constructor of the parent class, with its parameters for arguments super(inMC,xV,yV); } // method to change the motion direction when the object reaches the border // With 4 if() instructions to verify the object's position for each side private function bounceAtBorder():void { // Verify if the object has reached the right edge // Substracts half the object's width (this.insMC.width/2) from the Stage's width (this.insMC.stage.stageWidth) // (half because we created the MovieClip object with the registration center in the middle) if(this.insMC.x > this.insMC.stage.stageWidth-(this.insMC.width/2)) { // Set up the 'x' distance with the value resulted by the Stage's width minus half the object's width // Turns negative the value of the property used for horizontal motion (to change direction) this.insMC.x = this.insMC.stage.stageWidth-(this.insMC.width/2); xVel *= -1; } // Verify if the object has reached the bottom edge // Substracts from the Stage's height (this.insMC.stage.stageHeight) half of the object's height (this.insMC.height/2) if (this.insMC.y > this.insMC.stage.stageHeight-(this.insMC.height/2)) { // Set up the 'y' distance with a the value resulted by the Stage's height minus half the object's height // Turns negative the value of the property used for vertical motion (to change direction) this.insMC.y = this.insMC.stage.stageHeight-(this.insMC.height/2); yVel *= -1; } // Verify if the object has reached the left edge // (the 'x' distance smaller than half the object's width) if (this.insMC.x < this.insMC.width/2) { // Set up the value for 'x' distance half the object's width // Turns negative the property's value used for horizontal motion speed

this.insMC.x = this.insMC.width/2; xVel *= -1; } // Verify if the object has reached the top edge //(the 'y' distance smaller than half the object's height) if (this.insMC.y < this.insMC.height/2) { // Set up the value for 'y' distance half the object's height // Turns negative the property's value for vertical motion speed this.insMC.y = this.insMC.height/2; yVel *= -1; } } // Rewrite the "updatePosition()" method, defined in the parent class, Mover override protected function updatePosition(evtObj:Event):void { // Include the instructions of the "updatePosition()" method from the base class super.updatePosition(evtObj); bounceAtBorder(); // calls the "bounceAtBorder()" method, defined above } } }

- See the explanations in code. - Save this class with the name "MoverChild.as" in the same directory as "Mover.as". - In the FLA document in which the "sfer" MovieClip instance is created, right-click on the Frame 1 in the Timeline and choose "Actions". Delete any existing code in Actions panel, and add the following code:
// Create an instance of MoverChild class var obj2:MoverChild = new MoverChild(sfer, 2, 3); obj2.startMove(); // Call the "startMove()" method

- Notice that, even if the "startMove()" method does not exist in the "MoverChild" class, it can be called through this instance of the child class, because it's inherited from the parent class as if it was written in it. - If you press "Ctrl+Enter", the Flash Player will display a presentation like this.

In the child class you can also rewrite the properties and methods inherited from the parent class. In the example above, in the "MoverChild" subclass, the values of the 'xVel' and 'yVel' properties are modified, and the 'updatePosition()' method is rewritten; all defined in the "Mover" parent class. In the "updatePosition()" from child class we use the "super.updatePosition(evtObj)" expression to include the functionality of this method from parent class, then we added another instruction. In this way we keep the functionality of the original method, and also add new instructions. To rewrite a method use override keyword in the definition of that method in the child class. With this syntax:

override attribute function methodName() { // The code that will replace the original one }

- Rewritting a method does not affect the original in the parent class, the modifications are available only in the child class, respectively in its subclasses. - To keep using the initial code (from the parent class) in the rewritten function, include it with super.methodName(); in the body of the function in child class. - "super.methodName()" includes "methodName()" from the parent class. The super() function calls the constructor method of a parent class, it must contain a number of arguments equal to the number of parameter of the constructor from the parent class. If it's not added in the child class code, it will automatically be added by the program, but without arguments. So, if the constructor of a parent class contains parameters, you must add "super(parameters)" in the constructor of the child subclass. Creating subclass that extends child class

Sub-classes can also be extended in other child classes, so, the first child class becomes a parent of other subclasses extended from it, these are grandchildren of the original base class. The "grandchild" classes can not directly inherit the properties and methods of the "grandparent" class, but they inherit them through the class they are extended from.

To show how to create and use a subclass extended from a child class, we will continue with the example presented until now in this lesson. The base class "Mover" can move and stop the motion. Its child class, "MoverChild" changes motion direction when the object reached the borders. Now, we will define a child class extended from "MoverChild", named "MoverChildG". In this subclass we add an "effect of gravitation", that will pull the object down and slow it until it stops. - Because the "MoverChildG" extends "MoverChild" and not directly the base class, it inherits the capacity to not let an object leaves the borders. Open a new "ActionScript 3.0 Class" document, give it the name "MoverChildG", delete the initial code in it and copy the following code:
// Create the package (without name) package { // Import classes whose properties and methods will be called in this class import flash.display.MovieClip; import flash.events.Event; import MoverChild; // Import its parent class // Start defining the MoverChildG, subclass of the MoverChild class public class MoverChildG extends MoverChild { // Define this classes properties // with "private" attribute because they are used only in the code of this class

private var streng: Number; private var lastPosX: Number; private var lastPosY: Number; // Constructor // Besides the attributes necessary for the class from which it is extended, also add a "streng" (for motion power) // ('stren' having a default value, makes it optional when it is created an instance of this class) public function MoverChildG(inMC:MovieClip, xV:Number, yV:Number, streng:Number=1) { // Call the Constructor of the parent class (from which it is extended) super(inMC, xV, yV); // Assign the value of the "streng" parameter to the 'streng' property // The same name was given both the property and the parameter to better know it's role (but it can also have a different name) this.streng = streng; } // Rewrite the "updatePosition()" method, defined in the parent class override protected function updatePosition(evtObj:Event):void { // Include /Keep the initial code of this method and adds other instructions too super.updatePosition(evtObj); this.applyGravity(); this.applyFriction(); this.checkForStop(); } /* The internal functions are defined private, because they are only needed inside this class */ // Increas the speed on the Y axis with the 'streng' property private function applyGravity():void { this.yVel += this.streng; } // Add the gravitational coeficient G (0.98) to the speed on the X and Y axes // by multiplication, to gradually reduce their value private function applyFriction():void { this.xVel *= 0.98; this.yVel *= 0.98; } // The Function used to verify the moment when motion has stopped // calls the "stopMove" method from the base class // ("stopMove" deletes the record of the ENTER_FRAME event's detection, // not being necessary after stopping, it frees up memory occupied by this event) private function checkForStop():void {

// If the X and Y position is the same as the last recorded one if(this.insMC.x == this.lastPosX && this.insMC.y == this.lastPosY) { this.stopMove(); // Calls "stopMove" method } // Retains in 'lastPosX' and 'lastPosY' properties the last position this.lastPosX = this.insMC.x; this.lastPosY = this.insMC.y; } } }

- Detailed explanations about the instructions used in this class are in the comments in code. - Save this class with the name "MoverChildG.as" in the same folder as "Mover.as" and "MoverChild.as". - In the FLA document (from the same folder) where the "sfer" MovieClip instance was created, rightclick on the Frame 1 in the Timeline and choose "Actions", delete any existing code in the "Actions panel" and add the following code:
// Create instance of MoverChildG class var obj3:MoverChildG = new MoverChildG(sfer, 15, 30, 2); obj3.startMove(); // Call "startMove()" method

- If you press "Ctrl+Enter", the result will be the motion of the object as is shown in the following presentation (click on image).

From all these examples you can see how efficient is to use the inheritance. New things can be created, without to modify the base class, and without creating again its properties and methods.

You can also create classes that can not be extended. These classes are called "final class". To create a "final class", add the term final before the keyword class: For example: package { public final class ClassName { // Instructions ... } }

- The FLA and AS files with examples from this lesson can be downloaded from: Inheritance - Parent and Child classes.

Classes - Interface in ActionScript 3


Interface is a class used as a pattern, or template for classes with similar functions, that must respect a certain basic structure. Synthesized, the Interface is a class with a list of required methods that must be created in the classes where it is implemented. All the methods specified in the "Interface" must be defined in the classes where it's applied, having the same name, data type and parameters as indicated in the "Interface".
Creating an interface

The interface class is created in the same way as other types of classes, in a "package", saved in a separate AS document. The difference is that, instead of the keyword "class" you use the keyword "interface"; also, in its body you only write a list of methods, without code instructions. The general syntax is:
package { public interface InterfaceName { function methodName(prop1:DataType, prop2:DataType, ...):DataType; function otherMethod(prop1:DataType, prop2:DataType, ...):DataType; ........... } }

- When declaring the methods in an interface, their code or curly brackets are not added, neither an attribute, because in an interface class are added only the methods that will have the "public" attribute. - Properties can not be specified.

Here's an example of an interface, named "ITest", in which we specify 2 methods: "Links()" and "Tutorials()".
package { // Create interface public interface ITest { // A list with required methods function Links():void; function Tutorials(gen:String, nota:int):String } }

- This code must be added in an "ActionScript 3.0 Class" document (or "ActionScript 3.0 Interface"), write "ITest" at the class name and the file with this code must be saved with the name "ITest.as", in the same folder as the classes which will implement this interface.

Implementing interface
Once the "interface" was saved, you can create classes that implement the methods specified in the interface. To implement an interface, use the keyword implements and the interface name after the class name:
public class ClassName implements InterfaceName { // Instructions }

- "ClassName" must contain all the methods defined in "InterfaceName", with the "public" attribute, the number of parameters and their DataType established in the interface. The class can also contain other methods. In the following example, we create a class (named webDevelopment), in a new AS document, with the name "webDevelopment.as" and save it in the same folder as the "ITest" interface.
package { // Create class that implements the ITest interface public class webDevelopment implements ITest { // Define a protected property protected var site:String = 'coursesweb.net'; /* Define the required methods (Links and Tutorials), specified in interface */ // Returns in Output the value of the 'site' property public function Links():void { trace(this.site); } // Return the value of a variable that takes the transmitted arguments public function Tutorials(gen:String, note:int):String {

var re:String = gen+'-'+note; return re; } // creates an additional method // Displays in Output the argument received public function Diverse(val:*):void { trace(val); } } }

- The required methods ("Links()" and "Tutorials()") respect the exact parameters (number, order, data type) set in the "ITest" interface. Other methods (in this case "Diverse") and properties are optional, depending on each class role. - In the required methods, the name of the parameters does not matter, but the number, data-type and order must be the same as in "interface". To test this example, open a new Flash document, add in the "Actions panel" the following ActionScript code, than save it in the same directory as the interface and class above.
// Create an object instance of webDevelopment class var obj:webDevelopment = new webDevelopment(); // Call the methods obj.Links(); trace(obj.Tutorials('Flash', 8)); obj.Diverse(2010); // coursesweb.net // Flash-8 // 2010

- Because the "webDevelopment" class meets the conditions specified in the implemented interface (ITest), the script is functional. - If any of the conditions are not met in the class: such as not defining a method, adding an extra parameter, or declaring with other data-type; the script will return an error. Therefore, implementing an "interface" is usefull especially when you want to create multiple classes with similar roles, and you want them to have a minimal order and structure of methods, easier to remember. Interface as a data type

The interface can also be applied as a data type to variables (or function parameters). Then, the variable (or parameter) can represent an instance of the class which implements that "interface". You can understand it better from the following example, where we create another class (called WebProgramming) that implements the interface "ITest".
package { // Create class that applies ITest interface public class WebProgramming implements ITest { // Defining a protected property protected var adr:String = 'coursesweb.net/';

/* Defining the required methods (Links and Tutorials), specified in interface */ // Returns a string in Output public function Links():void { trace('Have a good life'); } // Returns the value of a variable "re" public function Tutorials(gen:String, nr:int):String { var re:String = nr+'-'+ this.adr+gen; return re; } } }

In the FLA document, write the following code in the "Actions panel".
// Create object instaces of the classes which implements 'ITest' var web_development:webDevelopment = new webDevelopment(); var web_programming:WebProgramming = new WebProgramming(); // Create a function with a parameter that has "ITest" interface as data type function courses(cls:ITest):void { // Call the methods set in ITest, through the "cls" parameter cls.Links(); trace(cls.Tutorials('flash', 4)); } // Calls the courses() function, passing for parameter the instances created above courses(web_development); // In Output displays: "coursesweb.net" and "flash-4" courses(web_programming); // In Output displays: "Have a good life" and "4-coursesweb.net/flash"

- Notice that calling the function with different arguments, reprezenting the class instances, the function uses the parameter "cls" as instance of the class (because it has "ITest" as data type), and can call the same methods ("Links" and "Tutorials") for each argument, because these methods are specified in "interface", so they must exist in each class that implements that interface, with the same type of parameters. - This technique helps you to not create the same function for each instance. You can also create child-interface that inherits the list of methods specified in a parent-interface, adding also additional methods if you want. The syntax to define a child-interface is:
public interface ChildInterface extends ParentInterface { // List of additional methods }

- The "ChildInterface" will contain the list of methods inherited from the "ParentInterface", and whatever else is added in it. It will not affect the ParentInterface. An "interface" can also be applied to child classes, using this syntax:
public ChildClass extends ParentClass implements Interface

- "ChildClass" can be an extension of any class, doesn't matter if the "ParentClass" implements or not an Interface. A class can implement multiple interfaces, separated by comma, like in this syntax:
public class ClassName implements Interface1, Interface2

If you modify an Interface which is already applied to a class, that class will not work.

- The FLA and AS files with examples from this lesson can be downloaded from: Classes - Interface in ActionScript 3.

Creating Object in ActionScript 3


The object class is the root of all the classes in ActionScript, all are an extension of the Object Class. Object is a dynamic class, meaning it permits adding new properties and methods, it enables you to create your own properties and methods.
Creating objects There are two ways to create objects in ActionScript 3. The most common form is with the syntax:
var objectName:Object = new Object();

- "objectName" becomes an object to which you can define its own properties and methods. Another way to create an object is with the following syntax:
var objectName:Object = {prop1:val1, prop2:val2, ...}

- "prop1", "prop2" represents the properties of the "objectName" object, and "val1", "val2" are their values. You can add as many "property:value" pairs as you want, separated by comma. If the value is a String, it must be writted between quotes, but numeric values do not. - This method is usually used when the respective object contains a simple list of data.

Adding and accessing properties

Once you have created an object with "new Object();", you can define its properties. The most common form to define properties of an object is with the dot operator (.):
objectName.property_name = value;

Another way is by using square brackets (as in associative Array):


objectName['property_name'] = value;

- When using square brackets, the property's name must be written between quotes (simple or double). - "value" can be a number, a string (between quotes), a variable, an array, or eaven the property of another object. To access the properties of an object, you can use the dot (.) operator, between the object's name and property (Object.property), or with the property between square brackets [] after the objects name (Object["property"]). it is indicated to use a single formula (without combining them), for a better clarity and understanding of the code. In general, for objects the dot (.) operator is used, square brackets are generally used for Array elements, thus avoiding confusion. Let's see an example with both formulas, to show their functionality.
// Create an object "obj" var obj:Object = new Object(); // Define 2 properties, the first with dot operator, the second with [] obj.site = 'coursesweb.net'; obj['courses'] = 8; /* This object can also be created by using the syntax with curly brackets var obj:Object = {site:"coursesweb.net", courses:8}; Represents the same object */ // Initialize a "TextField" instance var txt:TextField = new TextField(); // Adds in "txt" instance a Text that contains the values of the "site" and "courses" properties // For "site" uses [], and for "courses" uses the dot (.) operator txt.text = obj["site"]+ ' - '+ obj.courses; // uses "addChild()" to add /display the text in the Flash presentation addChild(txt); // coursesweb.net - 8

- If you add this script in a new Flash document, and press "Ctrl+Enter", the text "coursesweb.net - 8" will appear in the flash presentation".

Define and call methods

Basically, methods are functions. The difference between functions and methods is that a function can be called directly by using its name, but the method is accessed through an object (or instance) in which it is defined. Methods are defined with the dot notation (.). To define a method, add the name of the method after the object's name, and for its value you must associate a function.
Syntax:
objectName.methodName = functionName;

- "functionName" can be the name of a function you have created, or it can be a function created directly in the method definition, like in the following syntax:
objectName.methodName = function():DataType { ... function's code };

The value obtained when you call a method is the value returned by the function associated to the respective method. Here's an example. We create an object with a property (id) and two methods. For the first method ("getSum()") we associate a function created separately, and for the second method ("getID()"), the function is created directly in its definition.
// Create the function that will be associated to a method function f_sum(a:Number, b:Number):String { var sum:Number = a+b; return 'The sum is: '+ sum; } // Define the object "obj2" with a property "id", and two methods "getSum" and "getId" var obj2:Object = new Object(); obj2.id = 'tutorials'; obj2.getSum = f_sum; obj2.getId = function():String { var idul = 'Id: '+ this.id; return idul; }; // Initialize a "TextField" instance in a "txt2" variable var txt2:TextField = new TextField(); // Adds in "txt2" instance a Text that contains the values returned by the "getSum()" and "getId()" // - "\n" adds new row txt2.text = obj2.getSum(7, 8)+ "\n"+ obj2.getId(); // uses "addChild()" to display the text in the Flash presentation addChild(txt2);

- When the methods: "getSum()" and "getID()" are called, the program executes the code of the functions associated to them (each returns a string). - Notice that to associate the "f_sum()" function to the "getSum()" method, only the name was used (without the round brackets), but when the method is called, you must use parentheses, and you must take into account the parameters of the associated function. - Another important aspect in this example is the expression "this.id". The keyword this is usually used inside the method and always refers to the current object through which the method is called. "id" is the property of the object "obj2". So, the formula "this.id" returns the value of the "id" property of the current object (obj2). - If you add the script above in a new Flash document and press "Ctrl+Enter", in the Flash presentation will appear these two rows of text: The sum is: 15 The ID: tutorials Modify properties and methods The value of the properties and methods of an object created with "Object class" can be modified at any time, by applying the same formula used to create them: - For properties objectName.property_name = new_value; OR objectName["property_name"] = new_value; - For methods objectName.methodName = another_function; function():Tip { ... Another code };

or

objectName.methodName =

Here's an example. We define an object with a property "gen" and a method "Race()", then we change their value.
// defines "obj3" object, with the property "gen" and the method "Race()" var obj3:Object = new Object(); obj3.gen = 'Animals'; obj3.Race = function():String { return "Donkeys" }; // uses trace() to check their value trace(obj3.gen+ ' - '+ obj3.Race()); // Animals - Donkeys

// changes the values of "gen" and "Race()" obj3.gen = 'Birds'; obj3.Race = function():String { return "Pigeons" }; // checks again their value trace(obj3.gen+ ' - '+ obj3.Race()); // Birds - Pigeons

- You can see that the second trace() statement outputs a different result.

Delete properties and methods, verify their existance To delete a property or method of an object created with the "Object class", use the delete instruction, like in the following syntax:
delete objectName.element;

- "element" can be any property or method of the "objectName". If you want to check if a property or method is defined in an object (or class instance), use the in operator, with this syntax:
"element" in Class

- "element" must be added between quotes and can be any property or method from "Class" ("Class" can also be the name of an object created with 'Object class'). - This instruction returns true if the "element" exists in "Class", otherwise it returns false. In the following example is created an object (obj4) with a property "gen" and a method "Race()". We use the "in" operator to test their existance, then we delete them, and check again their existence.
// Define the "obj4" object with the property "gen" and the method "Race" var obj4:Object = new Object(); obj4.gen = 'Animals'; obj4.Race = function():String { return "Donkeys" }; // uses "in" to test their existance trace("gen" in obj4); // true if("Race" in obj4) { trace(obj4.Race()); // Donkeys } // Delete "gen" and "Race()" delete obj4.gen; delete obj4.Race; // checks again their existance trace("gen" in obj4); if("Race" in obj4) { trace(obj4.Race()); } // false

// Try accessing them trace(obj4.gen+ ' - '+ obj4.Race()); Race is not a function ...

// TypeError: Error #1006:

- Notice the effect of "in" and "delete", and how the "if()" instruction is used. To download the FLA files with the examples in this lesson, click: Creating objects in ActionScript

Nested Objects Traverse Object


Nested Objects
Nested objects are objects created inside another object. So, the property of an object (it's value) can be an Array or even another object. Let's see an example:.
// Create a main object "Courses", with 2 properties:"type" and "site", and a method "getCourse()" // The first property, "type", will have as value an Array with 2 elements // The second property "site", will have as value another object, which will have a property "url" // The method "getCourse()" will use an element from the array in "type" property, // and the property of the nested object var Courses = new Object(); Courses.type = ['lessons', 'tutorials']; // property with an Array value Courses.site = new Object(); // property which contains a nested object Courses.site.url = 'coursesweb.net'; // property of the nested object Courses.getCourse = function(nr:int) { // Method of the main object var sir1 = this.tip[nr]; // uses a value from the "type" property var sir2 = this.site.url; // uses the value of the "url" property (of the nested object) return sir1+ ' - '+ sir2 }; // Displays in Output the result returned by calling the method "getCourse()" trace(Courses.getCourse(1)); // tutorials - coursesweb.net

- The property "site" is defined as a sub-object in the main object (Courses); - Notice the expression used to call the property of the nested object "this.site.url", it accesses the "url" property which is defined in the "site" (the sub-object). "this" represents the current object in which the expression is added. - The expression "Courses.getCourse(1)" calls the "getCourse()" method and passes it the value of 1. The method uses this argument to get an element of the array in the "type" property, "this.tip[nr]". Traverse objects

You can traverse the elements of an object the same way as when traversing an associative Array, with the instruction "for..in" or "for each..in". Study the following example, and the comments in code.

Example with for..in


// define aunction to traverse objects // Takes 2 arguments: "obj" for the object which will be traversed, and "val" for the value that must be searched in it function parsObj(obj:Object, val:*):String { // define a variable to store the value returned by this function var re:String = 'no prop'; // defina a "for..in" loop to traverse "obj" for(var key:String in obj) { // If the value of the current element is the same as the value of "val" // adds in "re" the name of that property and stops the loop if(obj[key]==val) { re = key; break; } } return re; } // Define object with 2 properties ("courses", "tutorials") and a method "Sum()" var anObject:Object = new Object(); anObject.course = 'Flash'; anObject.tutorial = 'AS3'; anObject.Sum = function(a:Number, b:Number):Number { return a+b; } // Call the function "parsObj()", passing the object and value 'AS3' trace(parsObj(anObject, 'AS3')); // tutorial

- The "for(var key:String in obj)" loop stores in "key" the current property of the "obj", then, the "if(obj[key]==val)" checks if the value of this property is the same as the value of "val". - The "re" variable is defined with an initial value, to be returned in case the "if()" instruction doesn't find a value to match the "val". The code above will display in output the string "tutorial".

Example with "for each..in"


// Define object with 2 properties ("courses", "tutorials") and a method "Sum()" var anObject:Object = new Object(); anObject.course = 'Flash'; anObject.tutorial = 'ActionScript 3'; anObject.Sum = function(a:Number, b:Number):Number { return a+b; } // defina a "for each..in" loop to traverse "anObject" // Displays in Output the value of each element

for each(var elm:* in anObject) { trace(elm); }

This example will show in Output: function Function() {} ActionScript 3 Flash

Working With Objects from Library in ActionScript 3


To work in ActionScript 3 with an element added in the Flash Stage we use its instance name (the name written in the Properties panel, in the box whith "<Instance Name>"). In AS3 code you can also use objects stored in the Library panel (images, symbols), without adding their instance on the Stage. This is more advantageous because multiple instances of the same object from the Library can be added dinamically and interatively in the Flash presentation, using ActionScript. To be able to use an element from Library in AS3, it must be stored in a special class, then, this class can be accessed in your code to create and use new instances. To store the objects from Library in a class, you must enable the option "Export for ActionScript", which is found in the "Advanced" section, in the window which is opened by right-clicking on the object in the Library panel, and choose the Properties option (see in the image below).

Try the following example. 1. Open a new Flash document, draw a square on the Stage and convert it into a MovieClip Symbol (from Modify -> Convert to Symbol). You can give it a name, for example Square (it is usefuf to give a meaningful name for the Symbol, making it easier recognized in the Library panel). 2. The Symbol is automatically added in the Library panel. Delete the square on the stage and open the Library panel (from Window -> Library). 3. Right-click on the Symbol's name (Square) and choose Properties. Flash will open a window like in the image below. Click Advanced, to can access the options in the

advanced zone.

4. Check the "Export for ActionScript" button, it will store the Symbol in a class (whose name is added in the field "Class"), and gives the posibility to use it in the ActionScript script. Flash automatically adds the name of the Symbol in the Library as the class name. It can be modified, but usually it is better to have the same name for the class and object. This name appears also in the column "Linkage" in Library (as you can see in the image above). 5. Once the "Export for ActionScript" option is enabled and the class name is set (Square), press OK. The class that represents this object is created and can be used in ActionScript code. - "Square" becomes a child class of a base class, specified in the field Base class (in this case "flash.display.MovieClip"). - Now you can create and use in your ActionScript code Instances of the Square class, with the syntax: var instance_name:ClassName = new ClassName(); 6. Right-click on Frame 1 in Timeline, choose Actions to open the "Actions panel", and add the following code:
7. // Defines a function that creates an instance of the Square class 8. // with parameters for 'x' and 'y' distance, and rotation 9. function addSquare(dist_x:Number, dist_y:Number, rot_z:Number):void 10. { 11. // Creates instance of Square class 12. var ins_square:Square = new Square(); 13. 14. // Sets the distances 'x', 'y', and rotation 15. ins_square.x = dist_x; 16. ins_square.y = dist_y; 17. ins_square.rotationZ = rot_z; 18. 19. addChild(ins_square); // Add the instance in the presentation 20. } 21. 22. // call this function 3 times 23. addSquare(38, 38, 0); 24. addSquare(130, 130, -19); 25. addSquare(250, 220, -45);

- This code creates and adds in the Flash presentation three instances of the object Square, each with different values for the distances 'x', 'y' and for rotation. - Press "Ctrl+Enter" to see the result.

The Flash player will display three squares like in the image below.

- This technique can be used with any object added in Library (Symbols, images, sounds). The Class associated to an element from Library can be edited. You can add instructions and methods that will be applied to the instances created with that class. Right-click on the object in the Library panel, and choose Edit Class. Add the code you want, then save the file with this class in the same folder as the FLA document (the name of the file must be the same as the name of the class).

To download the FLA file with the example from this lesson, click: ActionScript with objects from Library.

Creating new events


Besides the predefined events in ActionScript 3 (MouseEvent, KeyboardEvent, etc.) you can also create other new events (Custom Events), by extending the EventDispatcher class. - "EventDispatcher" is the base class for events.

To learn how to create a new event, study the following example. We create a class (named Game) as an extension of the "EventDispatcher" class (see the explanations in code). Game Class
// Game Class (with a "Custom Event") package {

// Imports the classes whose methods are used import flash.events.*; // To be able to use /extend the EventDispatcher Class import flash.utils.*; // Necessary for setTimeout // Create the Game class which extends the EventDispatcher public class Game extends EventDispatcher { // Define a constant that will represent the name of the new event // Its value gives the name of the event public static const GAME_OVER:String = 'gameOver'; // Private property, used only in the class to store a counting private var sec:int = 0; // Constructor public function Game(end:int) { // Call the "count()" function with the property "sec" as argument count(this.sec); // The function "count()" inside the constructor function count(sec:int):void { // If the property 'sec' has the value of 3, calls the "endGame()" method if(this.sec==end) endGame(); else { trace(sec); // Displays in Output the value of the 'sec' parameter this.sec = sec+1; // Modify the value of the "sec" property // "this.sec" is the property, 'sec' is the function's parameter // Calls the function "count()" every second, with the property "sec" as argument setTimeout(count, 1000, this.sec); } } } // The private method, called when "sec" reaches the value of the "end" parameter // "end" is the constructor's parameter and must be passed when the instance of the classe is created private function endGame():void { // Trigger the event created and represented by this class dispatchEvent(new Event(Game.GAME_OVER)); } } }

- The Game class contains a constant "GAME_OVER" that will represent the event's name, a private property "sec" (used only in the class body) and a private method "endGame()" that will trigger the event created by this class.

- The constructor increments the value of the "sec" property every second, and displays the number in Output panel. When this number becomes equal with the value passed as argument when the instance was created, calls the method "endGame()", that will trigger the event "Game.GAME_OVER". - This class must be added in a "ActionScript 3.0 Class" document, then saved with the name "Game.as" in the same folder as the FLA document that will use it. In the Flash document add the following ActionScript code:
// Create an instance of the Game class var game:Game = new Game(3); // Register an event listener to detect the Game.GAME_OVER event game.addEventListener(Game.GAME_OVER, gameOverListener); // You can also use the value of the GAME_OVER constant ('gameOver', gameOverListener) // Function called when the event is triggered function gameOverListener (evt:Event):void { trace('The game is over!'); }

- The event created by the Game class ( Game.GAME_OVER ) is registered as any other type of event, with the "addEventListener()" method applied to this class instance. "Game" represents the event, and "GAME_OVER" is its name. - When the "sec" property of the Game class reaches the value of 3 ( or any other number added to 'new Game(nr)'), it calls the "endGame()" method, that triggers the event. This action is detected by the event listener registered with "addEventListener()", and will call the "gameOverListener()" function. - In Output will be displaied: 0 1 2 The game is over!. Usually the class that represents the event is used in conjunction with another class that access it when declaring the event.

To download the FLA file and "Game.as" with the example from this lesson, click: Creating new events

Creating XML data - E4X in ActionScript 3


XML (Extensible Markup Language) is a special format for structuring and storing data. It is similar to HTML in that it uses tags to mark up content. XML tags are used to organize data

in a predictable hierarchy. But XML tags (also called elements) are not predefined. You must define your own tags.
Here's a simple syntax of a code in the XML format:
<?xml version="1.0"?> <base> <tag attribute="value"> <tag_in attribute="value">Data stored</tag_in> </tag> </base>

- If you don't know what the XML documents are, study the tutorial from the page XML Documents. The XML format is used in general to store data, such as URLs of images and web pages, adresses and names of audio /video files and other. The XML content can be used/ modified in ActionScript with functions specific E4X, which belongs to the XML and XMLList classes. Data in the XML format can be used in ActionScript by loading them from an external file or created directly in the script.

Creating XML data with E4X


The name E4X is a nickname used in ActionScript for XML in the ECMAScript standard. It's the same XML access standard that's used in JavaScript 2.0. To create XML data in ActionScript code via E4X, we have two general options: 1. Write our XML data in literal form, just like a string, in a XML instance. 2. Create a new XML instance, and then add each element programmatically, by using the dot (.) operator, or with XML, XMLList methods. As a general rule, the XML structure must be added in an instance of the XML class. - An XML object represents a portion of simple XML data such as an element, text node, attribute, comments. - An XMLList is a numbered set, very much like an array, of XML objects..

1) Let's take a simple example. We create a XML fragment with an XML literal.
// The XML instance with the complete XML data var pics:XML = <imglist> <image id="1"> <url>dir/img1.jpg</url> <title>Title img1</title> </image> </imglist>; trace(pics); // Displays in Output the XML structure

- This code creates a XML data structure, in the "pics" variable, which stores the adress and title of an image. "trace(pics)" displays in Output this structure.

The line breaks and quotation marks in the XML literal are perfectly normal. ActionScript knows they are part of the XML data, and interprets them as such. Data within an XML literal can also be added through variables, so that element names, attribute names, text content, etc., can be generated dynamically and easier to modify. These variables must be enclosed between curly braces {}. See the following example, which creates the same XML data as the example above.
// Variables with data that must be added in XML var img_id:int = 1; var img_url:String = 'dir/img1.jpg'; var img_title:String = 'Title img1'; // XML instance with complete XML data var pics:XML = <imglist> <image id={img_id}> <url>{img_url}</url> <title>{img_title}</title> </image> </imglist>; trace(pics); // Displays in Output the XML structure

2) The following code creates the same XML format, but dynamically specifies each element (with the dot (.) operator):
// The XML instance with the root tag var pics:XML = <imglist/>; // you can also use: XML(<imglist/>); pics.image.@id = 1; // Creates the tag <image>, includes an "id" attribute with the value of 1 pics.image.url = 'dir/img1.jpg'; // Add in the <image> element a tag <url> pics.image.title = 'Title img1'; // Add in the <image> element a tag <title> trace(pics);

- This code creates and returns in Output the same XML structure as the one from the first example. Notice the way to create each element, the logic is pretty simple: - The base tag (named root) is created when the XML instance is declared, with the form: var var_name:XML = <tagName/> - The other elements are created by adding them in the XML instance, in an hierarchical form, separated by the dot (.) operator. - The attribute is added after the tag in which it must be included, but with a character "@" before it (to be recognized that it is an atribute element). Another way to add elements in the XML structure is by using the following methods of the XML, XMLList classes:

appendChild(childObj) - Appends the "childObj" to the end of the XML object's properties. insertChildAfter(child1, child2) - Inserts the "child2" after the "child1" in an XML object and returns the resulting object. insertChildBefore(child1, child2) - Inserts the "child2" before the "child1" in an XML object and returns the resulting object prependChild(childObj) - add "childObj" to the beginning of an XML object, before any existing elements for that object

- These methods are efficient when you want to add data before or after other existing data. Here's the same XML format from the examples above, this time created with XML methods.
// XML instance with the root tag var pics:XML = <imglist/>; // Add each element // First the tag <image>, then within it: <url> and <title> pics.appendChild(<image id="1"></image>); pics.image.prependChild(<url>dir/img1.jpg</url>); pics.image.insertChildAfter(pics.image.url, <title>Title img1</title>); trace(pics);

To download the FLA file with the examples in this lesson, click: Creating XML data with E4X.

Accesing XML data - E4X


E4X provides you with ways to access any data in a XML content, such as: tag names, text content, attribute names and values, comments, or processing instructions.
Accessing tags and attributes E4X offers two general sets of tools for accessing data in an XML format: 1. The XML and XMLList methods - attribute(), attributes(), child(), children(), comments(), descendants(), elements(), parent(), processingInstructions(), and text(). 2. Variable-style access with the dot (.), descendant (..), and attribute (@) operators. The most convenient is the second option (with dot), because it is easier to understand. But there are some elements that can be accessed only with XML methods. - the parent element is accessed with the method parent() - comments are accessed with comments() - processing instructions, with processingInstructions() - elements and attributes which contains rezerved characters in their name can only be accessed with XML and XMLList methods

The next example displays in a text area in the Flash presentation the data from an XML (using the dot (.) operator). 1. Open a new Flash document, create a text area on the Stage (with "Text Tool"), and give it the instance name "datexml" (in the Properties panel). To display the border of this text area, choose a color from "Container border color", in the Properties panel -> Container and Flow. See in the following image the location of this option, the text area on the Stage and the Instance name 'datexml'.

2. In the "Actions panel" add the following code:


3. // variable which stores the XML content 4. var pics:XML = <imglist> 5. <image id="1"> 6. <url>dir/img1.jpg</url> 7. <title>Titlu img1</title> 8. </image> 9. </imglist>; 10. 11. // Add in "datexml" (text area on the Stage) the data from XML 12. datexml.text = 'Root tag: '+ pics.name(); // Name of the root tag 13. datexml.text += '\n ID image: '+ pics.image.@id; // Value of 'id' in <image> 14. datexml.text += '\n Url: '+ pics.image.url; // data in <url> 15. datexml.text += '\n Image title: '+ pics.image.title; // data in <title>

- '+=' adds the value of an expression to the value of a variable and assigns the result to the variable. - '\n' adds a new row.

- Notice that the "name()" method is also used, it returns the name of the element to which it is applied (in this case the "pics" instance returns the root tag). The dot (.) operator must be combined with methods to work as efficiently as possible. For example, without using functions you can not access the name of a child element from an object.

The expression object.* obtains all the elements (tags) in "object", and with @* you can obtain the values of all the attributes in an element.
16. Press "Ctrl+Enter", the Flash Player will show in the text area the accessed XML data, like in the following picture:

The methods of the XML and XMLList classes access the XML data in a hierarchical structure of nodes, parent, and child. Here's the same data extracted from XML, but using methods.
// variable which stores the XML content var pics:XML = <imglist> <image id="1"> <url>dir/img1.jpg</url> <title>Title img1</title> </image> </imglist>; // Add in "datexml" (text area on the Stage) the data from XML datexml.text += 'Root tag: '+ pics.localName(); // Name of the root tag // Value of the 'id' attribute of the first child element (<image>) in root datexml.text += '\n ID image: '+ pics.children()[0].attribute('id'); // Data from the <url> element of the first child (<image>) in root datexml.text += '\n Url: '+ pics.children()[0].child('url');

// Data from the second element ([1] <title> ) of the first child (<image>) in root datexml.text += '\n Image Title: '+ pics.children()[0].children()[1];

- This code displays in the Flash presentation the same data as the previous example, in the image above. - "pics.children()[0]" returns the content of the first child element in the "pics" object (the first element has the index 0, the second 1, ...). - "attribute('id')" returns the value of the "id" attribute of an element. - "child('url')" returns data in the "url" element. Hierarchical methods (child, parent) are useful especially when you don't know the name of the elements. The complete list with XML methods that can be used in ActionScript can be found at the official page XML Class - AS3. The length() method can be used to get the number of tags or attributes in an element. For example: trace(pics.image.*.length()); // 2 (number of tags included in <image>) trace(pics.image.attributes().length()); // 1 (number of attributes in <image>) Using the descendant accessor

An instruction that is useful in E4X is the descendant accessor operator, which is written as a double dot (..), it gives the posibility to directly access all the descendants of an object (child nodes, grandchild nodes, ...). With the "descendant accessor operator" (..) you can get a list with all the elements or attributes with a certain name from all the descendants included in the object to which it is applied. The XMLList class has a method form of this operator called descendants(). This function behaves the same way as the double dot, but for attributes the method "attribute()" must also be added.

Here's an example with the double-dot operator and the "descendants()" method. See the explanations in code.
// variable which stores the XML content var pics:XML = <imglist> <image id="1"> <url>dir/img1.jpg</url> <title>Titlu img1</title> </image> <image id="2"> <url>dir/img2.jpg</url> <title>Title pt. img2</title> </image> </imglist>;

trace(pics..title);

// or

trace(pics.descendants('title'));

/* Returns all the tags <title> that are in any descendant in "pics" <title>Title img1</title> <title>Title pt. img2</title> */ trace(pics.descendants().attribute("id")); // or trace(pics..@id); // Returns 12 (value of the "id" attributes that are in each descendant in "pics") // Gets the second "id" attribute trace(pics..@id[1]); // 2

- The expression after "// or" shows the equivalent way to get the same result. Accessing comments and processing instructions from XML In the XML content you can also add Comments and Processing Instructions. XML comments take the form:
<!-- Comment -->

XML processing instructions take the form:


<?app Data with instructions ?>

- Usually, processing instructions are pieces of code that must be executed on the server. For example, for PHP it would be: <?php PHP Code ?> These two ancillary forms of data can be accessed using the XML class's instance methods: comments() and processingInstructions(). Both methods return a list with these elements. By default, the E4X parser ignores both comments and processing instructions. In order to make them accessible, we must set ignoreComments (for comments) and ignoreProcessingInstructions (for processing instructions) to false. They are static variables, set through the XML class. XML.ignoreComments = false; XML.ignoreProcessingInstructions = false;

In the following example we use the same FLA document created at the beginning of this lesson (with the "datexml" text area in it), but with other XML data, that contains two comments and two processing instructions in the root tag <site>. This example will display in the text field "datexml" the first comment and the second processing instruction. Delete any existing code in the "Actions panel", and add this script:
// makes the comments and processing instructions accesible

XML.ignoreComments = false; XML.ignoreProcessingInstructions = false; // Create an XML fragment that contains both comments and processing instructions var coursesweb:XML = <site> <!-- http://coursesweb.net --> <?php PHP code processing instructions ?> <!-- Courses and Tutorials --> <courses> <course id="1" title="PHP-MySQL">coursesweb.net/php-mysql/</course> <course id="2" title="JavaScript">coursesweb.net/javascript/</course> <course id="3" title="FlashActionScript">coursesweb.net/flash/</course> </courses> <?php PHP code ?> </site>; // define 2 variables to store the comments and processing instructions found directly in root (the tag <site>) // Variables are Object type because the data is also taken with this type var coms:Object = coursesweb.comments(); var insp:Object = coursesweb.processingInstructions(); // Adds in 'datexml' the first Comment and the second processing instruction datexml.text = coms[0]; datexml.text += '\n'+ insp[1];

- Notice that the variables "coms" and "insp" are defined as "Object" type, because in E4X the data is taken and stored as objects, with numeric indexing (starting from 0). The first object can be accessed with the index [0], the second object, with index [1], and so on. - After you press "Ctrl+Enter", the Flash Player displays the following result:

To obtain an XMLList representing all comments and processing instructions within an entire XML tree, use the descendants operator in combination with the properties wildcard, as follows: instance_xml..*.comments() instance_xml.descendants().processingInstructions() - They do not get the comments and processing instructions included directly in the root tag.

Filtering XML Data Another important ability that E4X has is the posibility to filter data from an XMLList object. To filter data in an XML format, use the syntax:
theXMLList.(conditional_expression)

- For each item in theXMLList, the conditional_expression is executed once. If the conditional_expression yields true for an item, that item is added to an XMLList that is returned after all items have been processed. Because filtering is applied to XMLList type objects, the XML data must first be added in an XMLList instance Example.
// variable which stores the XML content var coursesweb:XML = <site> <!-- http://coursesweb.net --> <?php PHP code processing instructions ?> <!-- Courses and tutorials --> <courses> <course id="1" title="PHP-MySQL">coursesweb.net/php-mysql/</course> <course id="2" title="JavaScript">coursesweb.net/javascript/</course> <course id="3" title="FlashActionScript">coursesweb.net/flash/</course> </courses> <?php PHP code ?> </site>; // create an XMLList instance that contains all the elements from <site> var site:XMLList = coursesweb.* // gets only the "course" tags that have the attribute id>1 var elms:XMLList = site.course.(@id>1); trace(elms); /* In Output it will display: <course id="2" title="JavaScript">coursesweb.net/javascript/</curs> <course id="3" title="FlashActionScript">coursesweb.net/flash/</curs> */ // gets only the tag that has in text the word "flash" var tag1:XMLList = site.course.(text().search("flash") != -1); trace(tag1); // coursesweb.net/flash/ // gets the "title" attribute in the tag that has id<3 and contains the word "php" var tag2:XMLList = site.*.(@id<3 && text().search("php") != -1).@title; trace(tag2); // PHP-MySQL

- The expression "site.course.(@id>1)" returns the elements from the tag <course> that has the "id" attribute higher than 1. - "site.course.(text().search("flash") != -1)" searches the string 'flash' in the <course> elements, and returns the elements that contains the text "flash". - "site.*.(@id<3 && text().search("php") != -1).@title" searches in "site" the elements that have the "id"

attribute smaller than 3 and in their text conteins the word "php", then returns the value of the "title" attribute of the element found.

Notice that pretty complexe filterings can be created to obtain exactly the elements you want. But to filter a list in which not all the tags have the attribute or child element specified in the filtering condition, you must use the hasOwnProperty(), to verify the existance of that attribute or child-element. Otherwise it returns and error. For example, the following code returns all the elements in "an_xml" that have the "nr" attribute higher than 7. an_xml..*.(hasOwnProperty("@nr") && @nr>7)

To download the FLA with the examples from this lesson, click: Accesing XML data - E4X.

Loading XML Data, Traversing XML Trees


Usually, in most programms, the data in the XML format is loaded from external files. ActionScript 3 contains special functions to load and use the XML content from an external file. To load data from a XML file, follow these general steps:
1. Create a URLRequest object containing the location of the external XML. 2. Create a URLLoader object, using as argument the object defined with "URLRequest" (this will load the file). 3. To the URLLoader object apply the addEventListener() with the Event.COMPLETE event (to detect when the data was fully loaded) 4. Define the function that must be called by the registered event. Within this function apply the property data to the "URLLoader" instance to get the loaded XML, and pass it to a new XML instance. - Once the XML data was loaded from the external file, and added in a XML instance, the elements and attributes in the XML content can be accessed and processed with E4X specific methods (presented in the previous lesson). Here's an example. First, create a file named "xmltest.xml" in which add the following XML code. This file must be saved in the same folder as the Flash document in which it will be loaded.

XML data for xmltest.xml


<?xml version="1.0"?> <site> <courses>

<course id="1" title="PHP-MySQL">coursesweb.net/php-mysql/</course> <course id="2" title="JavaScript">coursesweb.net/javascript/</course> <course id="3" title="FlashActionScript">coursesweb.net/flash/</course> </courses> </site>

In a new Flash document add the following ActionScript code (in "Actions panel"):
// Declare a empty XML instance var test_xml:XML; // Create object with the file's URL var url:URLRequest = new URLRequest('xmltest.xml'); // declare the object that load the file var loader:URLLoader = new URLLoader(url); // register an event listener that detects when the loading has finished, and calls the "getXml()" loader.addEventListener(Event.COMPLETE, getXml); // The Function getXml() called by the event listener function getXml(evt:Event):void { // If data is loaded (stored in the property "data" of the object "loader") if(loader.data) { // Delete the event listener, not being necessary anymore, and it frees up memory loader.removeEventListener(Event.COMPLETE, getXml); // Add the data in the XML instance test_xml = XML(loader.data); /* Accessing the XML loaded data */ var nr_c:int = test_xml.courses.*.length(); elements in <courses> (3) // Returns the name of the root tag trace(test_xml.localName()); // site // gets the number of

// gets data in the last element from <courses> (nr_c-1) trace(test_xml.courses.child(nr_c-1)); // coursesweb.net/flash/ } }

- Because the 'nr_c' variable stores the number of elements (tags) in <courses>, (nr_c-1) represents the index of the last element, and the expression "test_xml.courses.child(nr_c-1)" returns its content. - This example will display in Output: site coursesweb.net/flash/

Traversing XML Trees

Traversing an object means to access every node in that object and process it in some way. For example, if you want to search through an XML object looking for an element with a certain attribute, the object must be traversed to verify each element. To traverse every node in an XML tree (or in an XMLList), use the "for each ... in", statement:
for each (var elm:XML in ObjectXML..*) { // code to execute }

- ObjectXML..* - returns a list containing all of ObjectXML's descendants. - The "elm" variable will contain the current element. Let's see an example. We use the same XML document saved in the "xmltest.xml" file. We load the XML data, and create a "for each..in" statement to traverse the XML object looking for the element which has value of the attribute "id" equal to 2. If this element is found, outputs its name and text content.
// Declare a empty XML instance var test_xml:XML; // Create object with the file's URL var url:URLRequest = new URLRequest('xmltest.xml'); // declare the object that load the file var loader:URLLoader = new URLLoader(url); // register an event listener that detects when the loading has finished, and calls the "getXml()" loader.addEventListener(Event.COMPLETE, getXml); // The Function getXml() called by the event listener function getXml(evt:Event):void { // If data is loaded (stored in the property "data" of the object "loader") if(loader.data) { // Delete the event listener loader.removeEventListener(Event.COMPLETE, getXml); // Add the data in the XML instance test_xml = XML(loader.data); // traverse the nodes in every descending element (..*) in "test_xml" for each(var elm:XML in test_xml..*) { // If the current element has the attribute "id", with the value of 2 // outputs the name of that tag and its text content if(elm.hasOwnProperty("@id") && elm.@id==2) trace(elm.localName()+ ' '+ elm.text()); // Display: } course - coursesweb.net/javascript/

} }

- See the explanations in code. - The current element is stored in the variable "elm", and "elm.hasOwnProperty("@id")" checks if it contains the "id" attribute. Without this checking, if the current element does not have that attribute, the condition "elm.@id==2" will return an error. - "elm.localName()" returns the name of the "elm", and "elm.text()" returns its text content. - The code above displays in Output: course - coursesweb.net/javascript/

To traverse only the attributes in an XML objecr, use the following formula: for each(var atr:* in ObiectXML..@*) - For example, in the script above we can apply: for each(var atr:* in test_xml..@*) { if(atr==2) trace(atr.parent().localName()+ ' - '+ atr.parent().text()); } - "parent()" returns the parent element (the one in which it's included). - The result displayed is the same.

To download the FLA and "xmltest.xml" files with the examples from this lesson, click: Loading XML Data, Traversing XML Trees.

Editing, Changing XML - E4X


Besides the posibility to create, load and access XML data, E4X also has functions to edit, change and delete the XML data in ActonScript.

Changing the Contents of an Element and an Attribute Value


The content of an element and the value of an attribute can be easily changed by accesing these elements with the dot (.) operator, when the structure of the XML content is well known. Just access the respective element /attribute, and assign that element any new value (other than an XMLList or XML object). The value is converted to a string and replaces the element's content. See this example:

// define an XML instance to store the XML content var marplo:XML = <site> <courses> <course id="1" title="PHP-MySQL">http://coursesweb.net/phpmysql/</course> <course id="2" title="JavaScript">http://coursesweb.net/javascript/</course> <course id="3" title="Flash ActionScript">http://coursesweb.net/flash/</course> </courses> </site>; // modify the content in the second tag <course> (in <courses>) marplo.courses.course[1] = 'www.marplo.net/engleza/'; // Modify the "title" attribute in the second tag <course> marplo.courses.course[1].@title = 'English Language'; // Verify if the data was changed trace(marplo); /* It will display: <site> <courses> <course id="1" title="PHP-MySQL">http://coursesweb.net/phpmysql/</course> <course id="2" title="Limba Engleza">www.marplo.net/engleza/</course> <course id="3" title="Flash ActionScript">http://coursesweb.net/flash/</course> </courses> </site> */

- See the comments in code. Tthe content of an element and the value of an attribute can also be changed using the methods of the XML class. Here's the same changes to the XML content, but this time using XML class's methods.
// define an XML instance to store the XML content var marplo:XML = <site> <courses> <course id="1" title="PHP-MySQL">http://coursesweb.net/phpmysql/</course> <course id="2" title="JavaScript">http://coursesweb.net/javascript/</course> <course id="3" title="Flash ActionScript">http://coursesweb.net/flash/</course> </courses> </site>; // Add in a XMLList instance the element that will be modified // (it is easier when you work multiple times with the same element) // the tag "course" in the first child of the root tag var curss:XMLList = marplo.children()[0].child('course');

// Modify the content of the second element stored in the variable "curss" curss[1] = 'www.marplo.net/engleza/'; // Change the value of the 'title' attribute in the second element stored in the variable "curss" curss[1].attribute("title")[0] = 'English Language'; // Verify if the data changed trace(marplo);

- In Output panel will display the same result as the first example.

Either of these two options is good (the dot operator and @ character, or XML class methods), depends on how well the content and hierarchy of the XML format is known, as well as the context in which the modifications are made. They can also be combined, for example: marplo.*.child('course')[1].@title = 'English Language';
Adding new tags and attributes

When new tags must be added in a XML object, the XML class methods are usually used (or combined with the (.) operator), because the XML methods offer a better control over the place where the item is addded (before or after other existing elements in an object). For attributes, if their order in the tag doesn't matter, they are added mostly by using the (.) dot operator and the character '@'.

in the following example we add a new <course> tag, at the beginning of the elements in <courses> (with the "prependChild()" method). Then, with a "for()" instruction we iterate over every <course> tags, and add to each one a "nr" attriburte (see the explanations in code).
// define an XML instance to store the XML content var marplo:XML = <site> <courses> <course id="1" title="PHP-MySQL">http://coursesweb.net/phpmysql/</course> <course id="2" title="JavaScript">http://coursesweb.net/javascript/</course> <course id="3" title="Flash ActionScript">http://coursesweb.net/flash/</course> </courses> </site>; // Create a new XML instance with the new "course" element, then add it in <courses> var new_course:XML = <course id="0" title="HTML">www.marplo.net/html/</course>; marplo.courses[0].prependChild(new_course); // Add in a XMLList instance all the elements with the tags <course> var curss:XMLList = marplo.courses[0].course; // define a for() loop to iterate over every item in "curss"

for(var i:int=0; i<curss.length(); i++) { // Add a "nr" attribute, with the value of "i" curss[i].@nr = i; } trace(marplo);

- In output displays the following XML format (notice the new <course> tag and the "nr" attribute):. <site> <courses> <course id="0" title="HTML" nr="0">www.marplo.net/html/</course> <course id="1" title="PHP-MySQL" nr="1">http://coursesweb.net/php-mysql/</course> <course id="2" title="JavaScript" nr="2">http://coursesweb.net/javascript/</course> <course id="3" title="Flash ActionScript" nr="3">http://coursesweb.net/flash/</course> </courses> </site>

The XML class's methods used to add new elements are:


appendChild(childObj) - Appends the "childObj" to the end of the XML object's elements insertChildAfter(child1, child2) - Inserts the "child2" after the "child1" in an XML object and returns the resulting object insertChildBefore(child1, child2) - Inserts the "child2" before the "child1" in an XML object and returns the resulting object prependChild(childObj) - add "childObj" to the beginning of an XML object, before any existing elements for that object setChildren(XMLcode) - Replaces the content of the XML object with the "XMLcode" object.

Deleting elements and attributes To delete elements and attributes from an XML object, use the delete operator as follows:
delete XMLobject.element_or_attribute

- For example:
delete xmlObj.elm[0]; // Delete the delete xmlObj.elm[0].tag[1]; // Delete the <elm> in root delete xmlObj.elm[0].@atr; // Delete the tag <elm> in root delete xmlObj.elm.tag.@atr; // Delete the elements <tag> included in each <elm> in root delete xmlObj.*; // Delete all delete xmlObj.*.tag.@*; // Delete all element <tag> first tag <elm> in the root second <tag> in the first "atr" attribute of the first attribute "atr" of all the the elements the attributes of each

In the following example we delete the last <course> tag and the "id" attribute from all the "course" elements.
// define an XML instance to store the XML content var marplo:XML = <site> <courses> <course id="1" title="PHP-MySQL">http://coursesweb.net/phpmysql/</course> <course id="2" title="JavaScript">http://coursesweb.net/javascript/</course> <course id="3" title="Flash ActionScript">http://coursesweb.net/flash/</course> </courses> </site>; // gets the number of <course> elements in <courses> (to know the index of the last element) var nr_c:* = marplo.courses[0].course.length(); // Delete the last <course> tag (its index is [nr_c-1]) delete marplo.courses.course[nr_c-1]; // Delete the "id" attribute from all the <course> tags delete marplo.courses.course.@id; trace(marplo);

- After applying the delete instructions, the remained XML content (displayed in Output) is: <site> <courses> <course title="PHP-MySQL">http://coursesweb.net/php-mysql/</course> <course title="JavaScript">http://coursesweb.net/javascript/</course> </courses> </site>

The editing operations can be also combined with filtering instructions. For example: delete marplo.courses.course.(hasOwnProperty('@id') && @id==2).*; - Delete the content of the "course" element which has the attribute id="2". The following instruction: marplo.*.course.(hasOwnProperty('@id') && @id==2).setChildren(<newtag>Text</newtag>); - Replaces the content of the "course" element which has the attribte id="2" with "<newtag>Text</newtag>". To convert the XML data into a String object, use the toXMLString() method as folows:

ObiectXML.toXMLString()

- This method allows to use the XML content as a String. To convert a String with XML data into a XML object, add the string as argument to a new XML instance:
var ObiectXML:XML = new XML(stringXMLdata);

To download the FLA file with the examples from this lesson, click: Editing, Changing XML - E4X.

Working with XML Namespaces in AS3


Namespaces are used in XML to help group XML elements and attributes into sets of similar functionality; it is used especially in RSS. In the XML document, Namespace is defined with an attribute xmlns to which is assigned (with colon : ) a prefix (a name) for Namespace name, and a string for its value, which is usually a URI (Uniform Resource Identifier) address. The syntax is:
xmlns:namespaceName="URI"

For example:
<pictures xmlns:ns="http://coursesweb.net"> <ns:image>img1.jpg</ns:image> <image>img2.png</image> </pictures>

- "ns" represents the name of the Namespace, it can be any word. - "http://coursesweb.net" is the identification value for this Namespace (this can be any string, but usually it's a URI adresses, which can be non-valid URI).

The URI for an XML namespace doesn't have anything to do with a web site located there; it's only to provide a unique string.

Elements and attributes with the same Namespace name are considered as being part of the same group. Namespaces can be declared in the element which uses it or in the root. You can define multiple namespaces in the same tag.

Working with namespace in AS3


There are multiple XML class methods in ActionScript used for working with namespace:

namespace('prefix') - returns the value of the namespace that matches the "prefix" parameter. If there is no such namespace in the XML object, this method returns undefined. addNamespace(NSobject) - adds the namespace defined in a Namespace object (NSobject). removeNamespace(NSobject) - removes the given namespace (NSobject) for an XML object and all descendants. setNamespace(NSobject) - sets the namespace of an XML object to the one you provide in "NSobject".

In E4X, XML namespace attributes are not represented as attributes (they cannot be accessed via attributes() or someElement.@*). They are accessed via namespace() method. Example:
// Variable with XML data var galery:XML = <pictures xmlns:ns="http://coursesweb.net"> <ns:image>img1.jpg</ns:image> <image>img2.png</image> </pictures>; trace(galery.image[0].namespace('ns')); trace(galery.image[1].namespace('ns')); undefined // http://coursesweb.net // Error #1010: A term is

To add a namespace dynamically to an XML object in ActionScript, you must create the namespace in an instance of the Namespace class. The prefix (namespaceName) and the value of the namespace can be added as arguments when the instance is created:
new Namespace("prefix", "value_uri");

Then use this instance as argument in the "addNamespace()" method. Or you can create the Namespace instance without arguments, and then add the "prefix" and its value by using the properties of the Namespace class: prefix and uri. These properties can also be used to access and edit later the name and the value stored in the Namespace object.
var name_var:Namespace = new Namespace(); name_var.prefix = "namespaceName"; name_var.uri = "value_uri";

Let's see an example. We define a simple XML format, with two tags in the root, and an attribute in the second tag. Then we create a namespace and set it to the first element and to the attribute in the second tag.
// Variable with XML data var test:XML = <root> <tag>Text elm1</tag> <tag atr="val">Elm 2</tag> </root>; // define the instance with the namespace

var ns1:Namespace = new Namespace('ns', 'coursesweb.net/flash'); // Add the namespace in the XML object (in root) test.addNamespace(ns1); test.tag[0].setNamespace(ns1); // Sets "ns" to the first <tag>

// Sets "ns" at the "atr" attribute in the second <tag> test.tag[0].@atr.setNamespace(ns1); // Or: test.children()[1].@atr.setNamespace(ns1); trace(test);

- This example displays in Output the following XML format:


<root xmlns:ns="coursesweb.net/flash"> <ns:tag>Text elm1</ns:tag> <tag ns:atr="val">Elm 2</tag> </root>

- As you can notice, the namespace was added in the XML content, in the root tag, and set to the first <tag> and to "atr". tag*index+ accesses the tags without a namespace, so the "tag*0+" returns the first element without a namespace, not strictly the first element in the XML object. To avoid confusion that appears in these cases, to use the order in which the elements are in the XML object, you can use the "children()" method. For example: test.children()[1].@atr.setNamespace(ns1); Using the double-colon operator (::) E4X defines another operator for accessing nodes with namespaces: the double colon (::). With this operator you can access nodes (elements, attributes) that have the same namespace. First, use the namespace('prefix') method to add in a Namespace instance the nodes which have the "prefix" namespace, then you can access them with the double-colon (::) operator, using the following syntax:
XMLobject.instanceNamespace::node

To understand it better, see the following example:


// Variable with XML data var galery:XML = <pictures xmlns:ns="http://coursesweb.net"> <ns:image>img1.jpg</ns:image> <ns:image ns:title="Img 2">img2.png</image> </pictures> // Add in a namespace instance all the elements (and attributes) with "ns" var name_s:Namespace = galery.namespace('ns'); trace(galery.name_s::image[0]); trace(galery.name_s::image[1].@name_s::title); // img1.jpg // Img 2

- Notice in the XML format how the namespace is applied to elements and attributes (ns:tag , ns:attribute). The instance "name_s" stores the items which have the "ns" namespace (in a numeric order, like an

Array), and then these items are accesed with the (::) operator, as presented in the syntax above. The (::) operator can also be used to edit and delete the elements stored in the Namespace instance. For example:
galery.name_s::image[1].@name_s::title = 'Another title';

- Modify the value of the "title" attribute in the second <image> element. And the expression:
delete galery.name_s::image[0];

- Delete the first <image> element. Elements with namespace in a XML object can be accessed through hierarchical methods ( child((), children() ), or through a Namespace instance and the double-colon (::) operator. The expression "element[index]" accesses only the elements without namespace, as seen in the following example.
// Variable with the XML data var test:XML = <root xmlns:ns="coursesweb.net/flash"> <ns:tag>Text elm1</ns:tag> <tag ns:atr="val">Elm 2</tag> </root> // Returns the value of the first element, using tag[0] trace(test.tag[0]); // Elm 2 (it is the second, but the first without namespace) // Returns the value of the first element, using children()[0] trace(test.children()[0]); // Text elm1

To download the FLA file with the examples from this lesson, click: Working with XML Namespaces in AS3.

RegExp - Regular Expressions in ActionScript


RegExp (Regular Expresions) is a pattern describing the set of possible strings that can be formed with that pattern, following certain rules. These regular expressions use parenthesis (round, square, braces) and special characters that form rules for forming words, or any string. In ActionScript, the RegExp pattern is write within two forward slash characters "/" ( /regexp/ ). To start, let's see some simple patterns.

- The fallowing regular expression: /s[ak]y/ can form the fallowing words: say and sky (an expression added within square brackets "[ak]", is called class pattern) - A pattern for strings that may contain only vowels: /[aeiou]/ (by placing the letters that you want to match inside square brackets:). - If you wish to allow uppercase vowels, add them too, /[aeiouAEIOU]/ (or you can use the "i" modifier, /[aeiou]/i - modifiers are presented below). - For strings that may contain any letters written in lower case, you can write: /[abcdefghijklmnopqrstuvwxyz]/. Or you can use ranges with the dash character (-): /[a-z]/ (this expression means "a series of consecutive characters from 'a' to 'z'"). - Similarly, the pattern /[0-9]/ represent strings that contain only numbers. To match a certain number of characters, put the quantity between curly braces, adding the minimum and maximum number of allowed characters. - For example, the regular expression: /[aeiou]{2,4}/, matches any string that contain only vowels and has 2, 3 or 4 characters ("ai", "oue", "auio", etc.). To specify that the characters within square brackets may be repeated in the string, use "+" or "*" after square brackets. - For example, /s[ak]+y/ would match: sky, saay, saakyy, etc. To specify the repetition of a subpattern of a regular expression, place that subpattern between round brackets. - The fallowing RegExp, /(s[ak]y ){2,3}/ corresponds to a number of two or three repetitions of any of the strings: "say " and "sky ". This pattern would match: "say sky ", "say sky say ", etc. (Notice the space character after "y" in this RegExp, it must be the same in the matching strings, with a space after "y"). There are several special characters that are used in regular expressions. If a circumflex accent (^) is the first symbol added inside square brackets, it has the effect of reversing the regular expression placed between those parentheses. - So, /[^aeiou]/ will match any non-vowel string. - /[^a-z]/ matches any character that is not a lowercase letter. When this character (^) is placed outside the square brackets, it represents the beginning of the string or line. - The regular expression /^s[ak]y/ corresponds to sub-string "say" or "sky" only if they are at the beginning of the string subject. There is also the dollar sign ($), which marks the conclusion of a pattern, the end of the string or line. - /s[ak]y$/ will correspond to "say" or "sky" only if they are at the end of the string subject. Here is a list of more special characters and their role in regular expressions:

^ - Indicates the beginning of a string

$ - Indicates the end of a string . - Any single character except newline () - subpattern [] - class pattern (a character of the ones within square parentheses) [^] - any character except those in square brackets / - Escape character (disable the special role of the character in front of which is added) + - The character (or expression) before this sign should repeat at least one time (to infinite) * - The character (or expression) before this sign can repeat it 0 to infinite ? - The character (or expression) before this sign may repeat it 0 or 1 time | - Alternatives (or) {x} - Exactly "x" occurrences {x,y} - Between "x" and "y" occurrences {x,} - At least x occurrences \r - new row ("\r\n" for windows) \t - Tab

- For example, /[ho|ca]me/ corresponds to home and came words. To put these characters (+ , * , ? , < , > ( , { , [ , | ...) in a regexp pattern, disabling their special role, you must prefix them with a backslash character "\". For example, /[0-9]\*[0-9]/ matches a multiplication between two numbers ( "*" is no longer a repetition factor). Besides these characters there are special formulas for shortening regexp expressions:

\w - Alphanumeric characters plus "_". Equivalent: [a-zA-Z_] \W - Non-word characters. Equivalent: [^a-zA-Z_] \s - Whitespace characters. Equivalent: [ \t\r\n\v\f] \S - Non-whitespace characters. Equivalent: [^ \t\r\n\v\f] \d - Decimal digit characters. Equivalent: [0-9] \D - Non-digits. Equivalent: [^0-9]

- For example: /[\d\s]+/ matches strings that contain only numbers and white spaces. Here are some examples of regular expressions:

(.*) - represents all characters (by ".") repeated as often as possible (by "*") (fa|te)rms - matches "farms" and "terms" ^www.+net$ - strings that beginns with "www" and ends with "net" ^www\.[a-z0-9]+\.com$ - matches the "www.__.com" strings, the "__" can be any word that contains lowercase letters and numbers (^-\+[0-9]*) - any number that starts with "-" or "+" \<tag\>(.*?)\<\/tag\> - represents the content within <tag>...</tag> \<tag\>(.[^\<]+) - The string from <tag> till the first "</" ^([a-zA-Z0-9]+[a-zA-Z0-9._%-]*@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4})$ - Regular expression for email addresses

^(http://|https://)?([^/]+) - Regular expression for domain name of a URL

Besides the special characters and formulas used for shortening the regular expression, there are also other special letters called modifiers. They have a special role only if they are placed after the closing delimiter ("/regexp/mods"), and alter the behavior of a regular expression. The most used RegExp modifiers are listed below:

g - (global) - allows the expression to be used repeatedly on the source text until there are no more matches. When it is not set, the expression will return the first match. i - (ignore-case) - letters in the pattern match both upper and lower case letters (for caseinsensitive comparisons). m - (multiline) - change the role of "^" and "$". If "multiline" is not specified, they indicate the beginning and end of the text of the regexp, but when this modifier is added, they indicate the beginning and the end of the whole line. s - (dotall) - makes the dot metacharacter in the pattern matches all characters, including newlines. x - (extended) - If this modifier is set, whitespace in a RegExp pattern is ignored except when escaped or inside a character class.

You can add one or more modifiers at the end of the pattern. - Example: /\d{3}-[a-z]+/gi - searches for all "nnn-word" sub-strings ("nnn" is a 3-digit number and "word" can contain uppercase letters too). Usually, regular expressions are used in ActionScript for string matching and string replacing. ActionScript has special functions for these operations.

Applying Regular Expressions


Regular expressions in ActionScript 3.0 are instances of the RegExp class. Regular expressions can also be written as literals, between two slashes /.../. - The general form of a regular expression is:
var reg1:RegExp = /regular_expression/g; var reg2:RegExp = new RegExp("regular_expression", "g");

There are two ways to use regular expressions in ActionScript: using methods of the String class ("match()", "search()" "replace()"), or functions of the RegExp class ("test()" and "exec()"). test() - is used to test if some text matches a certain pattern. Returns true, or false if no match is found. - Syntax:
RegExp.test("string")

- Example:

// RegExp with expression that coresponds to the pattern: "word-nr3" (nr3 = a number with 3 digits) var reg:RegExp = /[a-z]+-\d{3}/gi; // Strings that will be checked var str1:String = 'CoursesWeb - Courses-008 and Tutorials-137'; var str2:String = 'AS3 Lessons-37'; // checks with test() if there is a substring in "str1" and "str2" that matches the pattern in 'reg' trace(reg.test(str1)); // true trace(reg.test(str2)); // false

As you can notice, the test() method returns true if in the tested string there is a substring that matches the pattern specified in "reg" variable; if no match is found, returns false. search() - (belongs to String class) searches for the specifed pattern and returns the index of the first matching substring. If there is no matching substring, it returns -1. - Syntax:
String.search(RegExp)

- Example:
// RegExp with expression that coresponds to the pattern: "word-nr3" (nr3 = a number with 3 digits) var reg:RegExp = /[a-z]+-\d{3}/gi; // Strings that will be checked var str1:String = 'CoursesWeb - Courses-008 and Tutorials-137'; var str2:String = 'AS3 Lessons-37'; // searches for the index of the substring that matches the pattern in 'reg' trace(str1.search(reg)); // 13 trace(str2.search(reg)); // -1

exec() - returns an object with the substring that matches a RegExp, and its index location. The location is stored in a property index. If there is no matching substring, it returns null. - Syntax:
RegExp.exec("string")

To find all the substrings that match a regular expression, use the exec() method with a while() statement. - Example:
// RegExp with expression that coresponds to the pattern: "word-nr3" (nr3 = a number with 3 digits) var reg:RegExp = /[a-z]+-\d{3}/gi; // the string to be checked var str1:String = 'CoursesWeb - Courses-008 and Tutorials-137'; // the object which will store the substrings and their location, returned by exec()

var exc:Object; // with while() and exec() checks the whole string in 'sir1' while(exc=reg.exec(str1)) { trace(exc[0]+ ' = '+ exc.index); // Returns: substring = location } /* Displays: Courses-008 = 13 Tutorials-137 = 29 */

If you not use a while() statement, exec() returns only the first substring (and its location) which matches the RegExp pattern. match() - returns an array with all substrings that match the specified pattern. If the global (g) is set, it returns all matches; otherwise it returns the first one. If no match is found, it returns null. - Syntax:
String.match(RegExp)

- Example:
// RegExp with expression that coresponds to the pattern: "word-nr3" (nr3 = a number with 3 digits) var reg:RegExp = /[a-z]+-\d{3}/gi; // the string to be checked var str1:String = 'CoursesWeb - Courses-008 and Tutorials-137'; // adds in an Array the substrings returned by match(), that match "reg" var ar_matc:Array = str1.match(reg); // if 'ar_matc' contains at least an item, displays the first substring found if(ar_matc.length>0) trace(ar_matc[0]); // Courses-008

replace() - replaces the substring (or substrings) that matches a specified RegExp, with another content. If the global (g) is set, the method searches and replaces all substrings that match the pattern. If the global (g) is not set, the method stops after the first substring. Returns the new replaced string, but without affecting the initial string. - Syntax:
String.replace(RegExp, 'new_content')

- Example:
// RegExp with expression that coresponds to the pattern: "word-nr3" (nr3 = a number with 3 digits) var reg:RegExp = /[a-z]+-\d{3}/gi; // the string to be checked var str1:String = 'CoursesWeb - Courses-008 and Tutorials-137'; // adds in a String type variabila the new string returned by replace() var str1_mod = str1.replace(reg, 'another_text');

// uses trace() to check the initial string and the new string trace(str1); // CoursesWeb - Courses-008 and Tutorials-137 trace(str1_mod); // CoursesWeb - another_text si another_text

- To download the FLA file with the examples presented in this lesson, click: RegExp - Regular Expressions in ActionScript.

Animation with the Timer class


This tutorial will show you how to create an animation whose motion is syncronized with a specified time interval. To make this type of animation with ActionScript, we use the Timer Class. The Timer is a class for executing code after a specified time interval. Each Timer object dispatches TimerEvent.TIMER events at a programmer specified frequency. The function called by TIMER event and executed at that frequency can be used to change the visual aspect of an object, so with frequent modifications of the object it can create the effect of animation. The animation created with TimerEvent does not depend on the number of frames per second FPS (like the one with ENTER_FRAME), but if the system or the Flash runtime is busy at the time a Timer is scheduled to execute its functions, the execution will be delayed. The general steps required to create an animation with the Timer class and the TimerEvent.TIMER are as follows: 1. Create a new Timer object, adding two arguments, the first argument sets the number of milliseconds between each time the timer event fires (frequency), the second atribute sets the total number of repetitions.
var name_var:Timer = new Timer(frequency, repetitions);

- The time interval (frequency) can also be set and changed with the property delay, and the number of repetitions with repeatCount (the value 0 indicates no limit) 2. Create a function to be invoked periodically when the TimerEvent.TIMER event is dispatched.
3. function functionName(evt:TimerEvent):void { 4. // code to execute }

- This function must define a single parameter whose datatype is TimerEvent. 5. Register an event listener with the Timer object for TimerEvent.TIMER, that calls the function created in Step 2:

instanceTimer.addEventListener(TimerEvent.TIMER, functionName);

6. Use the Timer class's method start() to start the timer. Once the timer is started, it begins dispatching TimerEvent.TIMER events according to the specified frequency and repetitions.
instanceTimer.start();

Another event in the TimerEvent class is TIMER_COMPLETE. This event type is dispatched when the number of repetitions is reached. The Timer class offers three methods for controlling the timer:

start() - Starts the timer, if it is not already running. stop() - Stops the timer. When start() is called after stop(), the timer instance runs for the remaining number of repetitions. reset() - Stops the timer and resets the number of repetitions back to 0

Let's make an example to apply these events and methods of the Timer class to create an animation. 1. Open a new Flash document, draw a rectangle (with "Rectangle tool") on the Stage, and convert it into Movie Clip (from Modify - Convert to Symbol). Open the "Properties panel", then in the box with "<Insance Name>" give the name "drept1" for this MovieClip instance (the rectangle on the stage) 2. Right-click on Frame 1 in the Timeline, choose Actions, and in the "Actions panel" add the following code:
3. 4. 5. 6. 7. var dimens:Number = 0.12; var move_y:Number = 23; var rotire:Number = 30; // sets a sizing coefficient (12%) // sets an Y motion distance // Degrees for rotation

// Create instance of Timer class, with the frequency half a second and maximum 6 repetitions 8. var jumpTimer:Timer = new Timer(500, 6); 9. 10. // The Function that will be called by the TimerEvent.TIMER 11. function jumpLand(evt:TimerEvent):void 12. { 13. // Modify the object's size with the coeficient value (%) from "dimens" 14. drept1.scaleX += dimens; 15. drept1.scaleY += dimens; 16. 17. drept1.rotation -= rotire; // rotates 18. drept1.y -= move_y; // moves vertically 19. } 20. 21. // The function that will be called by the TimerEvent.TIMER_COMPLETE 22. function atTimerComplete(evt:TimerEvent):void 23. {

24.

// Changes in an opposite way the values for sizing and vertical motion 25. dimens *= -1; 26. move_y *= -1; 27. 28. evt.target.reset(); // Resets the number of repetitions (to start from 0) 29. evt.target.start(); // Starts the TIMER again 30. } 31. 32. // register an event listener TimerEvent.TIMER, to "jumpTimer" instance 33. jumpTimer.addEventListener(TimerEvent.TIMER, jumpLand); 34. 35. // register an event listener TimerEvent.TIMER_COMPLETE, to "jumpTimer" instance 36. jumpTimer.addEventListener(TimerEvent.TIMER_COMPLETE, atTimerComplete); 37. 38. jumpTimer.start(); // Starts the TIMER

- When the number of repetitions reaches the specified value (in this case 6), the event TimerEvent.TIMER_COMPLETE is dispatched. In the function called by this event ( atTimerComplete() ) the animation's motion direction changes, the number of repetitions resets to 0, and the start() method is invoked to start again the TimerEvent.Timer. When the number of repetitions reaches again to 6, these operations repeat, and so on. This way is created a continuous movement of the object, on the vertical direction, up and down. - If you press "Ctrl+Enter", the Flash Player will display a presentation like this: - To increase the motion speed, set a lower value for the delay (the time interval).

- To download the FLA file with the animation presented in this lesson, click: Animation with the Timer class.

Вам также может понравиться