- More ActionScript Basics
- Block Statements
- Arrays
- Comparison Operators
- Logical Operators
- Boolean Operators
- Conditional Statements
- Looping
- Conditional Statements
- Dynamically Adding Library instances to the Stage
- Loading External Images and SWFs
Week 10 Example Files
Arrays
An array is a data structure similar to a variable, in that it allows you to hold values in memory. The difference is that a variable can only hold one value at a time, where an array can hold multiple values. Another distinction is that an array can hold values of multiple datatypes. Arrays are used in applications where you need to track an ordered list of values.
There are several different ways to create and populate an array. The simplest way is to create an empty array of indeterminate length:
var myArray:Array = new Array( );
You’ll notice the new operator here for the first time. This allows you to create a new instance of almost any ActionScript object. We’ll get into it more later!
If you put a value in the parentheses after Array in this statement, you are passing a parameter to the array. If you pass a single number, this will determine the number of spaces in the array:
var myArray:Array = new Array(5);
This creates an array with 5 spaces.
If you put anything besides a single number into the parentheses, the value(s) will be the initial values stored in the array.
var myArray:Array = new Array("Apple","Banana","Pear","Peach");
However, we usually create and populate an array all in one go using an array literal, a comma separated list of values enclosed by square brackets:
var arrayName:Array = [ value1, value2, value3 ]
Each value in array is an element. The place that the element holds within the array is its index. In order to access a specific element within the array, you must refer to it by the index number. Important to note is that the first element in an array has an index of 0, not 1.
To access an element in an array, use the following syntax:
arrayName[i];
Where i is the index number.
Here’s an example that puts it all together:
//define the array
var fruit:Array = ["banana", "orange", "papaya", "pineapple"];
//access the value of an array element
trace (fruit[0]);
You can find out the length of any array like this:
trace (fruit.length());
If you want to redefine a value in an array, you do this:
fruit[1] = "Guava";
You can add a value to an array either of these ways:
fruit[4] = "Guava";
or
fruit.push("Guava");
The advantage to the second method is that you don’t need to know how many values are already in the array.
You can delete a value in the array with the delete keyword:
delete fruit[1];
This will leave a blank space in the array.
If you want to get rid of that spot in the array completely, you must use the splice method of the Array object:
fruit.splice(1,1);
This will remove 1 element starting at index 1 of the array.
If you want to sort the contents of an array, you can use the sort method:
fruit.sort();
You can pass an options parameter to the sort method, here are just some of the options:
fruit.sort(Array.CASEINSENSITIVE);
fruit.sort(Array.DESCENDING);
fruit.sort(Array.DESCENDING | Array.CASEINSENSITIVE); // use two options
LiveDocs > Working with Arrays
LiveDocs > Array Reference
Comparison Operators
Last class we talked about mathematical operators. This week we are going to also make use of comparison operators, also called relational and equality operators. Here is a list:
- < Less than
- > Greater than
- <= Less than or equal to
- >= Greater than or equal to
- == Equality
- != Inequality
- === Strict equality
- !== Strict inequality
The operators are used to compare the values of the expressions to the left and right of them. Take note of the difference between the assignment operator (=) and the equality operator (==). = is used to assign the value of the expression on the right to the left. == is used to compare the equality of two values.
Livedocs > Operators
Boolean Logic and Operators
So far we’ve covered mathematic, comparison, and equality operators. The next set of operators that becomes useful to us are the logical operators. These will help us create more complex test expressions for use in both conditional and loop statements. Logical operators use boolean logic (whether something is true or false) to evaluate two expressions.
Logical OR
The logical or operator is expressed like this: ||. The use of this operator will return a value of true if at least one of two expressions to the left and right of the operator are true. The syntax for the OR operator is this:
expression1 || expression2
At runtime, the program will evaluate the values of expression1 and expression2. If either are true, it returns a value of true.
Logical AND
The logical AND operator is expressed like this: &&. The use of this operator will return a value of true if both expressions to the left and right of the operator are true. The syntax for the AND operator is this:
expression1 && expression2
At runtime, the program will evaluate the values of expression1 and expression2. It will only return a value of true if both expressions are true.
Both the && and || operators are useful when you want to test an expression within a range of values.
Logical NOT
The logical NOT operator is expressed like this: !. The use of this operator will return a value of true if the expression evaluates as false, and a value of false if the expression is true . Basically, it will return the opposite value. The syntax for the NOT operator is this:
!expression
This can be useful in situations where you need to toggle a value back and forth, like an on / off switch.
Conditional Statements
A conditional is a statement that is only executed at run time if a certain condition is met. There are two conditionals within ActionScript: if and switch.
The if statement
A basic if statement contains two block statements and a test expression:
if (testExpression) {
codeBlock1
} else {
codeBlock2
}
Here’s a example of the if statement in action:
//define variables
var age:Number = 21;
var greeting:String
// if statement
if (age < 21) {
greeting = "Sorry, no beer for you!";
} else {
greeting = "Have a cold one on me!";
}
//Output result
trace(greeting);
In the example above, the else clause provides an outcome in the case that the test expression is not true. You can also omit the else clause entirely, in which case the program will do nothing:
// if statement without else clause
if (age < 21) {
greeting = "Sorry, no beer for you!";
If you have a scenario in which you want to have more than two possible outcomes, you can chain your statements, adding an elseif clause:
if (testExpression1) {
codeBlock1
} else if (testExpression2) {
codeBlock2
} else {
codeBlock3
}
Livedocs > Conditionals
Loops
A loop is a block of code that is executed repeatedly based on a test expression. There are five types of loops: while, do-while, for, for-in, and for-each-in.
While Statement
A While statement executes while a test expression is true.
while (testExpression) {
codeBlock
}
You can see this looks very much like the if statement. The difference is that after the code block is executed the program returns to the beginning of the statement and evaluates the test expression again. If the test expression remains true, the code block is run again. This will continue until the test expression is evaluated as false.
If you create a while statement with a test expression that never evaluates as true, the loop will execute indefinitely, and Flash will generate a runtime error. Usually within the code block, you will include a statement that modifies the test expression. This will yield a false value for the test expression after the loop has executed the desired number of times:
var i:Number = 0;
while (i < 5) {
i = i + 1;
trace (i);
}
The variable name “i” is often used in a loop such as this. Like any variable, those used in a loop can have any name, but since this value is used as an incrementor, i is a recognizable shorthand for this use, and a common convention among programmers. There is also a new operator you can use in this case, the increment operator, which looks like this: ++. Placing this operator after a variable name will increase the value of the variable by one: i++. Our while loop example above can be simplified with the increment operator like so:
var i:Number = 0;
while (i < 5) {
i++;
trace (i);
}
There is also a decrement operator: –. When used after a variable name, it will decrease the variable value by one. So if you want your loop to count down to a value, instead of up, it could look like this:
var i:Number = 5;
while (i >= 0) {
i--;
trace (i);
}
do-while Statement
The do-while statement functions exactly the same as the while statement, except that the code block is placed before the test expression. This ensures that the code block will run at least once, even if the test expression evaluates as false the first time through. The syntax for the do-while statement is as follows:
do {
codeBlock
} while (testExpression);
For Statement
The for statement functions essentially the same as the while statement, but with a more compact syntax:
for (initialization; testExpression; update) {
codeBlock
}
The following example yields the same result as our original while statement, but in a much more compact way. Notice that the variable declaration and initialization, test case, and incrementor all take place within the test expression:
for (var i = 0; i <= 10; i++) {
trace(i);
}
Just like if statements, loops can be nested inside each other:
for (var i = 0; i <= 10; i++) {
trace("i="+i);
for (var j = 0; j <= 10; j++){
trace ("j="+j);
trace ("i*j="+j * i);
}
}
Using a loop with an array
Any type of loop statement is very useful for performing the same operation on all elements in an array. If we combine a for loop with the array we defined early, we can out all the values in the array sequentially:
for (var i = 0; i <= fruit.length; i++) {
trace(fruit[i]);}
Livedocs > Looping
Adding Objects to the Display List
There are two steps to adding a new Object to the stage. The Object can either be one of the built in classes (MovieClip, Sprite, TextField, etc) or an item from the library. First you must create the object instance using the new operator:
var myObject = new Object();
This instantiates the object, but it does not yet appear on the stage. You must add it as a child of the stage in order for it to become part of the Display List:
parentObject.addChild(myObject);
You can also put a new child at a specific depth, although you can’t skip depths. If you put a child at a depth where one already exists, that one will be bumped up a level.
parentObject.addChildAt(myObject,depth);
The parent object can be any DisplayObjectContainer that is already in the Display List. Remember, this includes the stage!
Remove Objects from the Display List
This is a one step process:
parentObject.removeChild(myObject);
Or
parentObject.removeChildAt(myObject,depth);
Livedocs > DisplayObjectContainer
Loading External Assets
ActionScript has the built-in ability to load external files via the Loader object, which, like MovieClip and Sprite is a subclass of the DisplayObjectContainer class. The Loader has a few special methods and properties that are tied to the loading and manipulating of an external file. You may load image files (jpg, png, or gif) and also other swf files, including swf files created with older versions of flash, with ActionScript 1.0 and 2.0.
The Loader works in conjunction with another class: URLRequest. This is a part of the flash.net package. When you create a new URLRequest you designate the path/filename of the asset to be loaded. This can either be an absolute path (http://www.mywebsite.com/image/myimage.jpg) or relative to the .swf file that will load the asset (image/myimage.jpg).
Once you have created instances of the Loader and URLRequest you can then use the load method of the Loader class to load the asset into the loader, something like this:
myLoader:Loader = new Loader();
myRequest:URLRequest = new URLRequest("images/myImage.jpg");
myLoader.load(myRequest);
A Loader instance can only hold one URLRequest at a time. If you load a new request into it, it will replace the existing request. However, you can have multiple Loader instances in a single movie.
Livedocs > Loader
Homework
Create a Flash movie containing grid of at least 9 images. To do this you should:
- Use a loop to load the images from external files and add them to the stage