Total hits since 4th Jan 2010

Thursday, February 25, 2010

Learning Action Script Fundamentals

Hi,
It has been written for those who requested me to cover basic concept of AS3 so that they can learn and start development by themselves. It is a part of that series. I will cover next topic further.

About ActionScript:

ActionScript is the programming language for the Adobe Flash Player run-time environment. It enables interactivity, data handling, and much more in Flash content and applications. ActionScript is executed by the ActionScript Virtual Machine (AVM), which is part of Flash Player. ActionScript code is typically compiled into bytecode format (a sort of programming language that’s written and understood by computers) by a compiler. The bytecode is embedded in SWF files, which are executed by the Flash Player, the run-time environment. A new ActionScript Virtual Machine, called AVM2 that uses a new bytecode instruction set and provides significant performance improvements. ActionScript 3.0 is based on ECMAScript, the international standardized programming language for scripting. ActionScript 3.0 is compliant with the ECMAScript Language Specification, Third Edition (ECMA-262).

Action Script Panel can be selected from File Menu -> New when you are planning to write code externally. You can also write code on Timeline by selecting a frame and pressing F9.
 


Variables and constants:
Since programming mainly involves changing pieces of information in the computer’s memory, there needs to be a way to represent a single piece of information in the program. A variable is a name that represents a value in the computer’s memory. As you write statements to manipulate values, you write the variable’s name in place of the value; any time the computer sees the variable name in your program, it looks in its memory and uses the value it finds there.

In ActionScript 3.0, a variable actually consists of three different parts:

• The variable’s name

• The type of data that can be stored in the variable

• The actual value stored in the computer’s memory

When you create a variable in ActionScript 3, you must use the var keyword.

var myVariableName; // var required

var age:int=30;

When defining a variable you must only use numbers, letters, dollar signs ($) and underscores (_) and a variable cannot start with a number. Whereas age2, _age2, and $age32 are valid, 32age is not valid for a variable name since it starts with a number.

You will also have to be sure not to create naming conflicts with your variable names and any internal variable names already defined in the current scope of your script. For example, when writing code in any timeline, you are writing code that is being defined for a MovieClip instance – the MovieClip instance that is represented by that timeline. If you try to define a variable with a name that is the same as a predefined MovieClip variable (or function) you will get an error.

The Flash CS3 Actions panel can sometimes be helpful in identifying conflicts since recognized keywords are highlighted as blue.

Data types:

In ActionScript, there are many data types that you can use as the data type of the variables you create. Some of these can be thought of as “simple” or “primitive” data types:

Simple or Primitive Data type:

• String: a textual value, like a name or the text of a book chapter

• Numeric: ActionScript 3.0 includes three specific data types for numeric data:

• Number: any numeric value, including values with or without a fraction

• int: an integer (a whole number without a fraction)

• uint: an “unsigned” integer, meaning a whole number that can’t be negative





• Boolean: a true-or-false value, such as whether a switch is on or whether two values are equal.

• *: untyped; // variable can have any type
The data type will give following output when it is checked using trace() function.

• var untyped:*; // (or no typing) undefined

• var boolean:Boolean; // false

• var number:Number; // NaN

• var integer:int; // 0

• var unsignedInteger:uint; // 0

• var string:String; // null

• var object:Object; // null

Any other Object type results in default value of null. It should be noted that values of the type object (any kind of object including arrays and objects created from custom classes) have a default value of null, not undefined. In fact objects in ActionScript 3 cannot be undefined. If they have no value, then they are null. Only with untyped variables or attempting to access variables that do not exist will get a value of undefined.

Number types are now unique in that they can no longer be undefined or null. If they have no value, they are seen as NaN ("Not a Number"). NaN is a tricky value, however. You can't really compare NaN with another NaN with the equality operator (==) because they probably won't be the same. If you ever need to check to see if a number is NaN, you should always use isNaN().

if (isNaN(myNumber)) // checks to see if Number is defined

There is one other type that is also not capitalized. This is the special void type. This was capitalized in ActionScript 2 but is no longer in ActionScript 3 since, like with int and uint, there is no specific definition associated with it. This type has not been seen so far as it only applies to functions.

Complex data type:

The majority of the data types defined in ActionScript could be described as complex data types, because they represent a set of values grouped together. For example, a variable with the data type Date represents a single value—a moment in time. Nevertheless, that date value is actually represented as several values: the day, month, year, hours, minutes, seconds, and so on, all of which are individual numbers. So while we think of a date as a single value (and we can treat it as a single value by creating a Date variable), internally the computer thinks of it as a group of several values that, put together, define a single date. Most of the built-in data types, as well as data types defined by programmers, are complex data types. Some of the complex data types you might recognize are: MovieClip, Sprite, SimpleButton, Date, Object, Custom class, Array etc.

You can recognize complex references, that is, any reference that requires a dot (.) or bracket access ([]) to reference the variable.

Type conversions:

A type conversion is said to occur when a value is transformed into a value of a different data type. Type conversions can be either implicit or explicit. Implicit conversion, which is also called coercion, is sometimes performed by Flash Player at run time. For example, if the value 2 is assigned to a variable of the Boolean data type, Flash Player converts the value 2 to the Boolean value true before assigning the value to the variable. Explicit conversion, which is also called casting, occurs when your code instructs the compiler to treat a variable of one data type as if it belongs to a different data type.

Explicit conversion example

var myBoolean:Boolean = true;

var myINT:int = int(myBoolean);

trace(myINT); // 1



Syntax:

Case sensitivity: ActionScript 3.0 is a case-sensitive language. Identifiers that differ only in case are considered different identifiers. For example, the following code creates two different variables:

var num1:int;

var Num1:int;

Dot syntax: The dot operator (.) provides a way to access the properties and methods of an object. Using dot syntax, you can refer to a class property or method by using an instance name, followed by the dot operator and name of the property or method.

For example, consider the following class definition:

Public class A

{

public myName:String=”Faiz”;

function A()

{

trace(“Constructor A”);

}

public function calculate(x:int);

{

trace(x+10);

}

}

var ins:A=new A();

ins.calculate(5);

Comments: ActionScript 3.0 code supports two types of comments: single-line comments and multiline comments.

var someNumber:Number = 3; // a single line comment

/* This is multiline comment

that can span more than one line of code. */



Iteration: Following loops available in AS3.



for

var i:int;

for (i = 0; i < 5; i++)

{

trace(i);

}



for..in

The for..in loop iterates through the properties of an object, or the elements of an array. For example, you can use a for..in loop to iterate through the properties of a generic object.

var myObj:Object = {x:20, y:30};

for (var i:String in myObj)

{

trace(i + ": " + myObj[i]);

}// output: // x: 20 // y: 30



You can also hide dynamic definitions from iteration using the ActionScript 3 myObj.setPropertyIsEnumerable(“x”,false) function. Now output will show only 30.


You can also iterate through the elements of an array:

var myArray:Array = ["one", "two", "three"];

for (var i:String in myArray)

{

trace(myArray[i]);

}// output: // one // two // three


What you cannot do is iterate through the properties of an object if it is an instance of a user-defined class, unless the class is a dynamic class. Even with instances of dynamic classes, you will be able to iterate only through properties that are added dynamically.
For example create a custom class A:

package

{

public dynamic class A {

public var age:Number=30;

function A()

{

trace("const@@@@@ructor A");

}

public function checkMe():void

{

trace("check Me A");

}

}

}
var ins:A=new A();

ins.sex=”male”;

for(var prop in ins)

trace(ins[prop])// output: male

You see that only property added dynamically is displayed in output Panel.

for each..in

The for each..in loop iterates through the items of a collection, which can be tags in an XML or XMLList object, the values held by object properties, or the elements of an array.

For example, as the following excerpt shows, you can use a for each..in loop to iterate through the properties of a generic object, but unlike the for..in loop, the iterator variable in a for each..in loop contains the value held by the property instead of the name of the property:

var myObj:Object = {x:20, y:30};

for each (var num in myObj)

{

trace(num);

}// output: // 20 // 30

You can iterate through an XML or XMLList object, as the following example shows:

var myXML:XML = <users> <fname>Jane</fname> <fname>Susan</fname> <fname>John</fname> </users>;

for each (var item in myXML.fname)

{

trace(item);

}/* output Jane Susan John */

You can also iterate through the elements of an array, as this example shows:

var myArray:Array = ["one", "two", "three"];

for each (var item in myArray)

{

trace(item);

}// output: // one // two // three

You cannot iterate through the properties of an object if the object is an instance of a sealed class. Even for instances of dynamic classes, you cannot iterate through any fixed properties, which are properties defined as part of the class definition.

while

The while loop is like if statement that repeats as long as the condition is true. For example, the following code produces the same output as the for loop example:

var i:int = 0;

while (i < 5)

{

trace(i); i++;

}



do..while

The do..while loop is a while loop that guarantees that the code block is executed at least once, because the condition is checked after the code block is executed. The following code shows a simple example of a do..while loop that generates output even though the condition is not met:

var i:int = 5;

do

{

trace(i); i++;

} while (i < 5); // output: 5



Conditionals:

ActionScript 3.0 provides three basic conditional statements that you can use to control program flow.

if..else

The if..else conditional statement allows you to test a condition and execute a block of code if that condition exists, or execute an alternative block of code if the condition does not exist. For example, the following code tests whether the value of x exceeds 20, generates a trace() function if it does, or generates a different trace() function if it does not:

if (x > 20)

{

trace("x is > 20");

}

else

{

trace("x is <= 20");

}

If you do not want to execute an alternative block of code, you can use the if statement without the else statement.

if..else if

You can test for more than one condition using the if..else if conditional statement. For example, the following code not only tests whether the value of x exceeds 20, but also tests whether the value of x is negative:

if (x > 20)

{

trace("x is > 20");

}

else if (x < 0)

{

trace("x is negative");

}

else

trace("x is 0");



switch

The switch statement is useful if you have several execution paths that depend on the same condition expression. It provides functionality similar to a long series of if..else if statements, but is somewhat easier to read.

For example, the following switch statement prints the day of the week, based on the day.

number returned by the Date.getDay() method:

var someDate:Date = new Date();

var dayNum:uint = someDate.getDay();

switch(dayNum)

{

case 0:

trace("Sunday");

break;

case 1:

trace("Monday");

break;



case 2:

trace("Tuesday");

break;



case 3:

trace("Wednesday");

break;



case 4:

trace("Thursday");

break;



case 5:

trace("Friday");

break;



case 6:

trace("Saturday");

break;



default:

trace("Out of range");

break;

}



Functions:

Functions define reusable chunks of code, or custom operations in ActionScript. By creating a function you can perform the same operation multiple times without having to write the same code over again for each time you want to use it. Instead, all you do is call the function using its function name.



There are two ways to define functions in ActionScript.



// Named function



function doubleNumber(num) {



return num*2;



}// Same function defined as an anonymous function



// defined within the variable doubleNumber



var doubleNumber = function(num) {



return num*2;



}

To use the function, you call it using parentheses (()).



var x:Number = 10;



trace(doubleNumber(x)); // traces 20



As with variables, named functions cannot be defined more than once for any one given timeline in ActionScript 3. Anonymous functions can reference multiple functions over time, but cannot be redefined with var as they are essentially variables. ActionScript 2 allowed you to change any function's definition anytime. In ActionScript 3, you can only change an anonymous function's definition.

When assigning type to functions, define typing information for both the parameter list (the comma separated list of values you can supply the function) as well as the return value, or the value that the function supplies after it's executed. When using an anonymous function definition, the variable the function is being assigned to would also be typed to Function.

// Named function

function doubleNumber(num:Number):Number {



return num*2;



}// Same function defined as an anonymous function



var doubleNumber:Function = function(num:Number):Number {



return num*2;



}

If a function does not return a value, then its return type should be void. When a function typed as void is executed, or simply fails to return a value with the return statement, its return value becomes undefined.



function returnsNothing():void {



// do nothing



}

trace(returnsNothing()); // traces undefined

The returnsNothing function above not only returns nothing, but also accepts no values – it has no parameter list. If you try to pass values into the function when it has no parameter list defined for it in ActionScript 3, you will get an error.

returnsNothing(3); // Error:

Parameters vs. arguments:

The difference between parameters and arguments is that parameters are the value used to define the function. Arguments are the actual values provided to the function during use. You can see arguments as being parameter values.

With ActionScript 3, you can also now define default values for your functions.

// Here, message parameter is optional

function usesDefault(message:String = "hello"):void {

trace(message);
}
usesDefault("test"); // traces "test"
usesDefault(); // traces "hello"

By using defaults you not only get to specify values for parameters not used by the function caller, but it also lets you define functions with optional parameters, or parameters that aren't required to be used. Those parameters that do not have default values must be provided when the function is called in ActionScript 3. Because of this, all optional parameters must be defined at the end of a parameter list. You cannot have a required parameter defined after an optional.

function usesDefault(message:String = "hello", num:Number):void {

// code
}

// Error: Required parameters are not permitted after optional parameters

function usesDefault(num:Number, message:String = "hello"):void {
// code
}// Correct; usesDefault needs at least 1 argument, accepts 2 at max

What if you wanted to allow a function to be called with any number of arguments? In ActionScript 2, you could do this simply by omitting any parameter list and referencing the arguments using the arguments object in the function. In ActionScript 3, having no parameter list means the function cannot be called with any arguments. Instead, you have to use a new parameter type known as …(rest). This parameter goes at the end of your parameter list (or it can represent your entire parameter list) and indicates that any number of arguments can be used when calling the function. The …(rest) parameter is written as …argumentsArrayName where argumentsArrayName is the name of the array that will contain the arguments passed.
// Using the ...(rest) parameter
function passAnything(...statements):void {
trace(statements.length +": "+ statements);
}
passAnything(); // traces 0:
passAnything(1); // traces 1: 1
passAnything("a", true, 0); // traces 3: a,true,0

Nested functions:

function getNameAndVersion():String

{

function getVersion():String

{

return "9";

}

function getProductName():String

{

return "Flash Player";

}

return (getProductName() + " " + getVersion());

}

trace(getNameAndVersion()); // Flash Player 9

Passing arguments by value or by reference:

To be passed by value means that the value of the argument is copied into a local variable for use within the function. To be passed by reference means that only a reference to the argument is passed instead of the actual value. No copy of the actual argument is made.

In ActionScript 3.0, all arguments are passed by reference, because all values are stored as objects. However, objects that belong to the primitive data types, which includes Boolean, Number, int, uint, and String, have special operators that make them behave as if they were passed by value.

For example, the following code creates a function named passPrimitives() that defines two parameters named xParam and yParam, both of type int.

Although xParam and yParam initially contain only references to the xValue and yValue objects, any changes to the variables within the function body generate new copies of the values in memory.

function passPrimitives(xParam:int, yParam:int):void

{

xParam++;

yParam++;

trace(xParam, yParam);

}

var xValue:int = 10;

var yValue:int = 15;

trace(xValue, yValue); // 10 15

passPrimitives(xValue, yValue); // 11 16

trace(xValue, yValue); // 10 15

Within the passPrimitives() function, the values of xParam and yParam are incremented,
but this does not affect the values of xValue and yValue, as shown in the last trace
statement. This would be true even if the parameters were named identically to the variables, xValue and yValue, because the xValue and yValue inside the function would point to new locations in memory that exist separately from the variables of the same name outside the function.

All other objects—that is, objects that do not belong to the primitive data types—are always passed by reference, which gives you ability to change the value of the original variable.

For example, the following code creates an object named objVar with two properties, x and y.
The object is passed as an argument to the passByRef() function. Because the object is not a primitive type, the object is not only passed by reference, but also stays a reference. This means that changes made to the parameters within the function will affect the object properties outside the function.

function passByRef(objParam:Object):void

{

objParam.x++;

objParam.y++;

trace(objParam.x, objParam.y);

}

var objVar:Object = {x:10, y:15};

trace(objVar.x, objVar.y); // 10 15

passByRef(objVar); // 11 16

trace(objVar.x, objVar.y); // 11 16

The objParam parameter references the same object as the global objVar variable. As you can see from the trace statements in the example, changes to the x and y properties of the objParam object are reflected in the objVar object.

No comments:

Post a Comment