Monday, August 23, 2010

Loop statements in AS3

Today is all about loops!

In this tutorial we are going to learn some very useful loop statements that are often used when making applications.

The for loop.

This one is probably the most common loop statement. Basically, you have a variable that automatically changes and performs a certain action every time it changes. Here's the syntax:

for (starting position; condition; action){
what to do}

And an example:

for (var i:int=0; i<10; i++){
trace("Test" + i);
}

This is a really simple piece of code, which just traces 10 lines of text in the output window, such as Test0, Test1, etc, up to Test9. Why Test9 and not Test10? Because once i is 10, it isn't smaller than 10, and that's exactly what our condition requires.

We can use this loop to dynamically create objects, manage arrays, do anything that needs to be repeated to be done. It usually saves time too.

The while loop.

The while loops is pretty similar to the for loop. Let me show you:

while (condition){
what to do
}

Let's try getting the same Test0-9 results, but using this type of loop.

var i:int=0
while(i<10){
trace("Test"+i);
i++
}

The do... while loop.

The do while loops is just like the while loop, with one exception - the action is done once before checking the condition, that means your action will happen at least once.

do {
what to do
}while(condition);

Example:

var i:int=0
do {
trace("Test"+i);
i++
}while(i<10);

The for... each in loop.

All the previous loop statements are used to perform an action repeatedly. This and the next loop are used for other purpose - you 'feed' the loop an object, and it tells you the values of all its properties.

For example, let's create an object and give it some properties, then retrieve the values using the for each in loop.

var customer:Object = new Object();
customer.fullname = "Thomas Anderson"
customer.age = 28
customer.telephone = "555-666-7777"

for each(var prp in customer){
trace(prp);
}

The code returns all the properties of customer object. The prp variable (doesn't have to be called prp) returns the value for each property.

The for... in loop.

Almost the same as the previous loop. The previous loop returns the values of properties, while this one returns the names of the properies.

var customer:Object = new Object();
customer.fullname = "Thomas Anderson"
customer.age = 28
customer.telephone = "555-666-7777"

for (var prp in customer){
trace(prp);
}

There you go. Hope this helped!

Thanks for reading!

No comments:

Post a Comment