| Flash ActionScript Programming
Basics |
 |
| Contents
|
 |
 |
|
Introduction
|
| This course is adapted from the book "C++
Primer " by Stanley Lippman.
There are currently two versions of Actionscript.
Actionscript 1.0 (AS 1.0) is the version
that works with Flash MX. Actionscript
2.0 (AS 2.0) is the new language that
ships with Flash MX 2004. Most items
in these tutorials will cover both AS
1 and AS 2. Where there is a difference
I will indicate it. Actionscript 1.0
will work with Flash MX 2004 but Actionscript
2.0 will not work with Flash MX. |
 |
|
|
 |
 |
|
Getting
started: writing and compiling a script
|
To enter actionscript code, open the
Actions window by hitting the F9 key or
selecting menu item "Window" - "Actions",
and start writing in that window.
Start Now. Open the Actions window and
type in this code:
var myNumber;
What you have done is a simple VARIABLE
DECLARATION. You have reserved space in
memory where some information/data is to
be stored.
Now write this in place of above.:
var myNumber = 10;
You have assigned a value to the variable.
i.e. stored the value 10 in the variable
myNumber.
The trace( ) function prints whatever
is between the parentheses to the output
window. It displays the value of the
argument of trace. To sequence text and
variables in a trace function use "+" to
add text to number and variables etc.
e.g.
trace("some Text " + someVariable);
So, here is our complete script,
var myNumber = 10;
trace("The value is " + myNumber);
Now execute or run the script. To execute
a script hit the keys "Control +
Enter" together, or use menu item "Control" - " Test
Movie".
After a script is written, the next step
is to compile it. Compiling means to
write to byte code that Flash understands.
The compiler has 2 jobs:
- error checking - the compiler will
examine the script for language correctness
or errors.
- Translate what we have to instructions
that the machine can understand.
|
|
|
 |
 |
|
Statements
|
|
A Statement is an expression
terminated by a semi-colon (";").
A statement in AS is similar to a sentence
in the English language. E.g.
var score;
score = 80;
trace(score);
Lets analyse the above script
-
is a declaration
statement. It tells the machine "we
exist"
-
Assignment(=) statement.
Assigns the value 80 to the computer
memory space associated with the
variable "score". Here
we have initialised score. We have
given it an initial value.
-
- prints the value
of score to the output window.
Do it now and hit Control+Enter.
Different values can be placed in
the boxes for each name. The name is
called a variable. It can be created
or thrown away at any time. When you
declare a variable, you set up a space
in memory for it and also leave a space
(connected with it) for a variable's
value.(8, 16, "Frodo", whatever).
What we have used so far as variables
has been numbers. There are a number
of variable types (called datatypes)
The main datatypes are Numbers (35),
Strings ("a bunch of text")
and Boolean (true or false).
Let's do another example. Write this
in the actions window:
var string1 = "This is a test";
trace(string1);
What did you get in the output window?
Try another:
var isTrue = true;
trace(isTrue);
|
 |
|
|
 |
 |
|
Comments
|
Comments are helpful lines that are
not compiled.
- They help readers understand our
program,
- summarize a function's algorithm,
- identify the purpose of a variable,
or
- clarify a segment of code.
There are two types.
- Multiple Lines ( /* */ )
/*
An explanation of a section of code
or
a coder's name and date
and other stuff
*/
- Single Line delimiters (//)
// number of record
var recordNum ;
|
 |
|
|
 |
 |
|
Operators
|
Operators are signs that do
something to variables on either side of
them. Here are the arithmetic operators:
|
Operator
|
Name
|
Example
|
| * |
Multiplication |
X* Y |
| / |
Division |
X/Y |
| % |
Modulus |
X % Y |
| + |
Addition |
X + Y |
| - |
Subtraction |
X - Y |
The Modulus operator(%) computes the
remainder of division between 2 integers.
e.g. 5 % 2 = 1
5/2 = (2*2) + 1(remainder)
Try it out! Ex1.
var x = 3;
var y = 5;
var mult1 = x * y;
trace(x + " times " + y + " = " +
mult1);
ex2
var min = 35;
var max = 239;
var addition = min + max;
trace(min + " plus " + max
+ " = " + addition;
You get the idea. Try all the operators
and start writing your own scripts.
|
 |
|
|
 |
 |
|
Equality, relational
and logical operators
|
These operators evaluate to
true or false
Evaluates to true only if both its operands
evaluate to true. E.g.
x = 5;
if(x>0 && x < 10){
something = true;
}
trace(something);
BOTH MUST BE TRUE.
Evaluates to true if either of its operands
evaluate to true. E.g.
x = 5;
If(x>0 || x<4) {
something = true;
}
trace(something);
EITHER CAN BE TRUE
|
Operator
|
Name
|
Example
|
|
!
|
Logical NOT
|
(!hasFired)
|
|
<
|
Less than
|
x < y
|
|
>
|
Greater than
|
x> y
|
|
< =
|
Less than or equal to
|
x <= y
|
|
> =
|
Greater than or equal to
|
x >= 24
|
|
==
|
Equality
|
if(hasFired == true)
|
|
!=
|
Inequality
|
If( x != 7)
|
|
&&
|
Logical AND
|
x >0 && x < 10
|
|
||
|
Logical OR
|
x< 0 || x > 20
|
|
Assignment Operator ( = )
|
The effect that an assignment has is
to store a new value in the left operand's
associated memory storage space e.g.
x = 7;
This statement means that the value 7
is assigned to the variable x.
|
Increment and decrement Operators
( ++ and -- )
|
The increment (++) and decrement (--)
operators are a shortcut way of adding
or subtracting 1 from a variable. E.g.
Prefix increment - ++c; // c = c+1
Postfix increment - c++;
The prefix form of ++ increments the
value of the variable before that value
is used.
stack[++top] = val;
//Is equivalent to the following 2 lines
top = top +1;
stack[top] = val;
The postfix form of ( --) decrements
the value of top after that value is
used.
stack[top--] = val;
//Is equivalent to :
stack[top] = v;
top = top -1;
The syntactic form is:
Expression1 ? expr2 : expr3 ;
If expression1 evaluates to a true condition,
then expression2 is evaluated, otherwise
expression3 is evaluated. E.g.
x = 2;
y = 5;
max = x<y ? 100 : 10;
trace(max);
Bitwise operators operate on the value
to base 2 (binary). Operands must be
integers.
Left Shift ("<<") -
shifts the bits of the left operand some
number of positions to the left. e.g.
someNum = 1;
SomeNum = someNum<<1;
SomeNum = someNum<<2;
Right Shift (">>")
SomeNum = someNum >>3;
The leftShift operator inserts "0" from
the right.
The Right Shift operator inserts "0" from
the left.
|
 |
|
|
 |
 |
|
Variables (AS
2.0)
|
A variable is identified by a user-supplied
name. Each variable is of a particular
data type. E.g.
Var num:Number;
" Number" is a type specifier. A declaration can follow the template:
var variableName:DataType;
-
The use of the ":Datatype" is
not strictly enforced in AS2 but
I strongly recommend it.
-
A variable can be
composed of letters, numbers and
underscore. Upper and lower case
letters are different.
-
Variables need to
be initialised. I.e. given an initial
value.
var myNum:Number; //Declaration
myNum = 0; //Initialisation
-
In AS 1.0, variables
are not strictly typed and can change
types.`
|
 |
|
|
 |
 |
|
DataTypes (AS
2.0 only)
|
Variables in AS 2.0 can be
given strict datatypes such as a Number
or a String or a Boolean. e.g.
var myNum:Number;
var myString:String;
var isTested:Boolean;
In AS 1.0 there is no strict datatyping.
A number can become a String and vice versa.
e.g.
num = 10;
num = "Test";
Strict datatyping can capture errors.
|
 |
|
|
 |
 |
|
Compiler Errors
|
- Syntax errors - e.g. var numberOne:
- Spelling Mistakes - var mc:MoveiClip;
- DataType Errors - (AS 2.0)
var num1:Number;
var str1:String;
num1 = "Steve";
str1 = 27;
|
 |
|
|
 |
 |
|
Flow control
|
An if statement tests a condition. If it
is true, then a set of actions is executed.
Otherwise, the set is ignored or bypassed.
Here is a template :
If(expression){
Statement1;
}
Here is an example :
var x = 23;
if(x>3){
trace("x is greater than 3");
}
If .. else allows for a kind of either
.. or condition.
Template:
If(expression){
Statement1;
}else{
statement2;
}
If expression is true then statement1
is executed.
If expression is false then statement2
is executed.
e.g.
var x = 2;
if(x > 3){
trace("condition is true");
}else{
trace("condition is false");
}
A switch statement is an alternative
to complex nested if .. else statements
switch(variable){
case 1:
//Statement1;
break;
case 2:
//Statement2
break;
default:
//statement3;
break;
}
The variable to be evaluated is inserted
into the switch argument. If the first
variable's value is 1 then statement1
is evaluated. A break statement is inserted
after it so that the switch statement
is terminated. The default label is the
condition for "everything else".
var tester:Number;
tester = random(3);
switch (tester) {
case 1 :
trace("tester = 1");
break;
case 2 :
trace("tester = 2");
break;
case 3 :
trace("tester = 3");
break;
default :
trace("Out of range");
break;
}
|
 |
|
|
 |
 |
|
Loops
|
A loop cycles over a body
of code as long as the condition remains
true.
template:
while(expression){
statement;
}
The statement is executed as long as
the conditions is true. E.g.
var x =0;
while(x < 10){
trace(x);
x++;
}
a do.. while loop executes the statement
once before the condition is evaluated.
Template:
do{
//Statements to be executed;
}
while(condition);
E.g.
var x =0;
do{
trace(x);
x++;
}
while (x < 10);
a for loop is used most commonly to step
through a fixed length data structure
such as an array.
Template:
for(init-statement; expr2;expr3){
// Statements;
}
e.g.
for(var i=0; i<10; i++){
trace(i);
}
the first statement initialises a looping
variable
3. sets the condition
3. increments the looping variable( also
could be something like i=i+2)
|
 |
|
|
 |
 |
|
Functions
|
A function is a named unit,
in which statements are logically grouped.
It usually contains the following parts:
- Function Name - e.g. function someName(
)
- Argument list - is enclosed within
parentheses after the function name.
It contains a comma-separated list
of 0 or more arguments. Arguments are
passed to the variable with the same
name as the argument inside the function.
- Return Type - the datatype of what
the function can evaluate to.
- The function Body - is enclosed within
a pair of braces { } and contains a
sequence of statements.
Here is a template. For AS 1.0 :
Function functionName(arg1, arg2, arg3){
// statements go here
return something if not void return type;
}
example1 (AS 1.0). Type this and compile
(Control+Enter):
function test1(arg1, arg2){
// arg1 is passed to the variable with
the same name
// in the next line I.e. arg1
trace(arg1);
trace(arg2);
}
// call function
test1(3,"Steve");
Notice that to call a function we write
the function name and the argument lists
in parentheses. Template to call a function:
functionName(arg1, arg2);
Example 2 with a return value (AS 1.0)
function returnTest(arg1){
var num = arg1 * 10;
return num;
}
// call function
trace(returnTest(5));
ex. 3
// returns the absolute value of number
function abs(number){
return( i < 0 ? -i : i);
}
// call the method
trace(abs(-350.95);
ex 4
// return the smaller of two values.
function min(num1,num2){
return(num1 <= num2 ? num1: num2);
}
trace(min(27,45));
|
 |
|
|
 |
 |
|
Functions
in AS 2.0
|
Functions in AS 2.0 are a
little different. AS 2.0 allows the setting
of specific datatypes. Here is an example
:
Function avgReturn(arg1:Number):Number{
Var num = arg1 * 5;
return num;
}
The template for an AS 2.0 function could
be :
Function functionName(arg1:DataType,
arg2:DataType):ReturnType{
// statements go here
return something ;
}
Void is used to specify that there is
no return type. E.g.
function noReturn(arg1:Number, arg2:String):Void{
trace(arg2 + " is a string and " +
arg1 + " is a number");
}
// call function
noReturn(5,"Steve");
|
 |
|
|
 |
 |
|
Arrays
|
An array is a collection of
objects . Individual objects are not named
but accessed by its position in the array.
Try this!
var theArray = new Array(5,4,8,2,1);
for(var i = 0;i<5;i++){
trace(theArray[i]);
}
Elements are numbered beginning with "0".
In the above array
theArray[0] = 5
theArray[2] = 8
Length is a property of Array. It tells
how many elements are in the array. So
, from above,
theArray.length = 5 |
 |
|
|
 |
 |
|
Classes
|
(As 2.0 only)
A class is a user-defined datatype, an
aggregate of named data elements, and
a set of operations to manipulate that
data. A class definition consists of
two parts:
- The class head - composed of the
keyword class and a name
- the class body - enclosed by braces,
contains the member definitions
A class name represents a new data type
. e.g.
class Dog{
// data members
var name:String;
var age:Number;
// class method
function setAge(age1:Number){
age = age1;
}
}
Constructors allow us to create an instance
of a class . e.g.
var rusty:Dog = new Dog();
// the dot operator (".") allows
us to access members and methods of that
class.
rusty.setAge(7);
rusty.name = "Rusty";
Go here for more information on classes
and OOP programming check out our tutorial
on Flash
MX 2004 Actionscript 2.0 Class Tutorial.
|
 |
| This tutorial provided by www.video-animation.com. |
|
|