Introduction to ActionScript 2.0/Control Statements

Introduction to ActionScript 2.0
Properties and Methods Control Statements Event Handling

Key concepts:


  • Control statements
  • Select statements and conditions
  • Switch statements
    • default, break;
  • For loops
  • Arrays
  • while and do ... while loops
  • for ... in loops
  • Using arguments with conditions and loops

Sometimes, we need to do a certain action many times. Sometimes, we don't want to perform an action in certain situations, but want to in others. This chapter is about control statements, which control how statements are executed.

What are selection statements? edit

A selection statement, also known as a conditional statement, is a type of control statement that allows you to perform one action if a value is true, and another action if a value is false. The Boolean value that determines which action will be taken is called the condition.

How can I use if? edit

Consider the following example:

Code Result
var isHappy:Boolean = true;
if(isHappy){
     trace("I am happy!");
}

I am happy!

In the above code, the words 'I am happy!' is traced if isHappy is true. What if we wanted to trace 'I am unhappy.' if isHappy is not true?

Code Result
function traceMood():Void{
     if(isHappy){
          trace("I am happy!");
     } else {
          trace("I am unhappy.");
     }
}
var isHappy:Boolean = true;
traceMood();
isHappy = false
traceMood();

I am happy!
I am unhappy.

In the above code, we used else to trace the words 'I am unhappy.' if isHappy is false or null. If the <Now suppose we want to trace 'Meh.' when we're neither happy nor unhappy. Here's the code for that:

Code Result
function traceMood():Void{
     if(isHappy){
          trace("I am happy!");
     } else if (isHappy == false){
          trace("I am unhappy.");
     } else {
          trace("Meh.");
     }
}
var isHappy:Boolean;
traceMood();

Meh.

In the above code, the computer first determined whether isHappy was true. Since it wasn't, it went on to the second part. Figuring out that isHappy was neither true or false, it went on to trace 'Meh'. Note that one cannot use the ! operator here because !isHappy simply means 'isHappy is not true', which is different from 'isHappy is false'.

To conclude, the syntax for selection statements is:

if(condition){
     Statements if the first condition is true;
} else if(condition){
     Statements if the second condition is true;
} ...
... else {
     Statements if none of the conditions is true;
}

Callers and callees[check spelling] are often used with selection statements. Here's an example showing the use of callers with a selection statement:

Code Result
function someCallee(){
     if(arguments.caller == someCaller){
          someNumber++;
          trace("No, *I* get to say that Hello World line!");
          arguments.caller();
     }
}
function someCaller(){
     trace("Hello world!");
     if(someNumber == 5){
          someCallee();
     }
}
var someNumber:Number = 5;
someCaller();
someCallee();

Hello world!
No, *I* get to say that Hello World line!
Hello world!

In this example, someCaller is called and traces 'Hello world!'. Since someNumber is 5, it calls someCallee. someCallee increases someNumber, traces the jealous line, then calls someCaller again. someCaller then annoys someCallee by tracing 'Hello world!' again. However, since someNumber is now 6, it does not trace someCallee again. The last line does nothing as someCallee only works when the caller is someCaller. This technique can avoid the accidental calling of functions outside the intended area.

Do not attempt to remove the selection in someCaller! If you do so, it will be like having two mirrors facing each other, resulting in an infinite loop. We will discuss infinite loops later in this chapter.

What are switch statements? edit

Sometimes, we have several conditions and it would be infeasible to make an if statement for every single one of them. In this case, we may use a switch statement. The syntax is as follows:

switch(variable){
     case value:
     Statements in this case;
     break;
     ...
     default:
     Statements if none of the cases are satisfied;
}

Look at the following example for an illustration of what is happening:

Code Result
var today:Number = 5;
switch(today){
     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;
     case 7:
     trace("Sunday");
     break;
     default:
     trace("That's not a valid day.");
}

Friday

The computer detects that today = 5 and traces the corresponding string, Friday. If the day were 0 or 8 or anything that isn't 1-7, Flash will execute the default action, i.e. trace 'That's not a valid day.'.

Note that the break; statement tells the computer to break out of the switch statement. If the break; statements are not included, the computer will continue executing the statements of the cases below it. For example:

Code Result
var today:Number = 5;
switch(today){
     case 1:
     trace("Monday");
     case 2:
     trace("Tuesday");
     case 3:
     trace("Wednesday");
     case 4:
     trace("Thursday");
     case 5:
     trace("Friday");
     case 6:
     trace("Saturday");
     case 7:
     trace("Sunday");
}

Friday
Saturday
Sunday

What are loops? edit

Sometimes, we need to perform an action many times. This is where loops come in handy.

How do I use a for loop? edit

A for loop has a variable called a loop counter that changes constantly. When the loop counter no longer meets a certain condition, the loop will stop. The syntax of a for loop is as follows:

for(declaration and initialisation of the counter; condition; change in the counter){
    Statement to be repeated;
}

For example:

Code Result
for(var i:Number = 0; i < 10; i += 2){
     trace("Wikibooks is awesome.");
}

Wikibooks is awesome.
Wikibooks is awesome.
Wikibooks is awesome.
Wikibooks is awesome.
Wikibooks is awesome.

The following steps were involved:

  1. i is set to zero.
  2. The computer traces the sentence since 0 < 10 is true. i increases by 2 and becomes 2.
  3. The computer traces the sentence since 2 < 10 is true. i increases by 2 and becomes 4.
  4. The computer traces the sentence since 4 < 10 is true. i increases by 2 and becomes 6.
  5. The computer traces the sentence since 6 < 10 is true. i increases by 2 and becomes 8.
  6. The computer traces the sentence since 8 < 10 is true. i increases by 2 and becomes 10.
  7. The computer breaks the loop since 10 < 10 is false.

Like with switch statements, it is possible to break the loop with a break; statement:

Code Result
var someVariable:Number = 3;
for(var i:Number = 0; i < 5; i ++){
     trace("Wikibooks is awesome.");
     someVariable ++;
     if(someVariable > 5){
          break;
     }
}

Wikibooks is awesome.
Wikibooks is awesome.
Wikibooks is awesome.

In this example, the loop was broken before i could equal 5 because the selection statement broke the loop.

Sometimes, we only want to stop the iteration of the loop, and not the entire loop. We use the continue statement for this:

Code Result
var someVariable:Number = 3;
for(var i:Number = 0; i < 10; i ++){
     trace("someVariable:" + someVariable);
     if(someVariable >= 5){
          continue;
     }
     someVariable++;
}

someVariable:3
someVariable:4
someVariable:5
someVariable:5
someVariable:5
someVariable:5
someVariable:5
someVariable:5
someVariable:5
someVariable:5

In this example, someVariable only increases if it is lower than 5.

When creating loops, one must be very careful not to create infinite loops. Infinite loops crash applications (warning: do not try this at home):

Code Result
var someVariable:Number = 3;
for(var i:Number = 0; i > -1; i ++){
     trace("Wikibooks is awesome.");
     someVariable ++;
     if(someVariable > 5){
          break;
     }
}

Application crashes!

What are arrays? edit

An array is an object the contains, well, an array of objects. It can store practically any object from numbers, Boolean values and strings to MovieClips, TextFields and sounds. These objects are called array elements. There are several ways to use the array's constructor function. In this chapter, we will only use the one without parameters.

Code Result
var months:Array = new Array();
months[0] = "January";
months[1] = "February";
months[2] = "March";
...
months[11] = "December";
trace(months[0]);

January

The position of an array element is called its index. Indices start with 0, not 1. We can access an array element using the syntax arrayName[index]. In the example, we didn't put in any parameters into the months. The computer only initialises a blank array.[1] Note that it is not optional to call the array's constructor function as you can't assign any elements to an undefined variable.

We will learn to manipulate arrays in the second section. For now, let's focus on using loops with arrays. The following example shows how to use for loops with arrays:

Code Result
var dogs:Array = new Array();
dogs[0] = "Spot";
dogs[1] = "Lucky";
dogs[2] = "Max";
...
dogs[9] = "Rover";
for(var i:Number = 0; i < dogs.length; i++){
     dogs[i] = dogs[i] + "is a good dog.";
     trace(dogs[i]);
}

Spot is a good dog.
Lucky is a good dog.
Max is a good dog.
...
Rover is a good dog.

The above loop adds the string 'is a good dog.' to the end of each element and traces it. Note that the length property of an array is the number of elements in it, or 9 in this case.

What is the arguments object? edit

In the chapter about functions and earlier in this chapter, we briefly examined the arguments object. Let's go back to it.

arguments is actually a funny type of array. It contains all the arguments passed on to the function (note that this may be different from the number of parameters declared). Look at the following example:

Code Result
function grabStrings(string1:String, string2:String, string3:String, string4:String):Void{
     trace(arguments.length);
     trace(arguments[0]);
}
grabStrings("foo", "bar", "baz");

3
foo

In this example, we first traced the length of the arguments object, which is 3 (there being three arguments passed: foo, bar and baz). We then traced the first argument, 'foo'. Now let's use a loop with it:

Code Result
function traceStrings(string1:String, string2:String, string3:String, string4:String):Void{
     for(var i:Number = 0; i < arguments.length; i++){
          trace(arguments[i]);
     }
}
traceStrings("foo", "bar", "baz");

foo
bar
baz

In the above example, we don't need to worry about tracing 'undefined' because the loop only lasts for the length of the arguments object.

What are while and do ... while loops?? edit

while loops allow us to specify a condition without using a counter. The syntax is:

while(condition){
     Statements if the condition is true;
}
Code Result
var months:Array = new Array();
months[0] = "January";
months[1] = "February";
months[2] = "March";
...
months[10] = "December";
var i:Number = 0;
while(months[i].substring(months[i].length - 4, months[i].length) == "uary" ){
     trace(months[i++]);
}

January
February

You don't have to understand how the condition works yet. Just take for granted that it returns true if the month ends in 'uary'. In this script, the computer will keep tracing the month until it reaches a month that doesn't end in 'uary', or 'March' in our example.

It is even easier to fall into the trap of infinite loops with while loops. Try to avoid them!

do ... while loops are similar except it ensures that it will always perform the action on the first time. For example:

Code Result
var days:Array = new Array();
days[0] = "Monday";
days[1] = "Tuesday";
days[2] = "Wednesday";
days[10] = "Sunday";
var i:Number = 0;
do{
     trace(days[i++]);
} while(days[i].length > 6 );

Monday
Tuesday
Wednesday
Thursday

In this example, the first element, Monday, gets traced, even though it is exactly six letters long. The loop stops at Friday, which is also exactly six letters long but isn't invited to the club as it isn't the first element.

How do I use a for ... in loop? edit

Apart from for loops, there's another type of loop called for ... in loops. It loops through all the 'loopable' properties of a class. For arrays, this refers to all the elements. Whether a variable is 'loopable' depends on its visibility, which we'll cover in the third section. The syntax is as follows:

for(Declaration of the counter without initialisation in Target object) {
    Statements to be executed;
}

The target object can be any composite data type. Let's rewrite the dog loop as a for ... in loop:

Code Result
var dogs:Array = new Array();
dogs[0] = "Spot";
dogs[1] = "Lucky";
dogs[2] = "Max";
...
dogs[9] = "Rover";
for(var i:String in dogs){
     dogs[i] = dogs[i] + "is a good dog.";
     trace(dogs[i]);
}

Spot is a good dog.
Lucky is a good dog.
Max is a good dog.
...
Rover is a good dog.

In the above, the computer loops through all the elements of dogs, adds 'is a good dog.' at the end, and traces. Note that although i is a string, Flash automatically converts it into the index.

Now let's try again with an Object instance.

Code Result
var spot:Object = {species:"chihuahua", colour:"brown"}
for(var i:String in spot){
     trace(spot[i]);
}

chihuahua
brown

In this case, Flash looped through both visible properties of spot (species and colour) and returned their values.

Conclusion edit

So far, we've gone through five chapters. In every case, you, the programmer, are the only person to input into the application. However, the purpose of ActionScript is to create an interactive application where the end user can also input into the system. In the next chapter, we will cover the most important way to do this: through event handling.

Notes edit

  1. Because of the existence of a global function Array(), you don't have to put the 'new' before Array() if you don't want to.