RSS link icon

.

Actionscript loops explained


This Flash action script tutorial is about loops, loops is a common well known tool. Loops are used to get something done a specific amount of times, or until a condition is changed.

 

actionscript loops tutorial

 

I will show you a couple of examples later on, but for now here is how a simple loop would look like with text instead of code.

for (counter; condition; action) {
	The things you want done in the loop.
}

In this first loop we specify a condition usually a maximum number, and when the condition has reached the number the loop stops.

while (condition) {
	Something you want done.
}

This is even more simple you define a condition, it an be basically anything, then while this condition is true it will loop over and over again.

do {
	Something you want done.
} while (condition)

This does exactly the same thing as the while condition, but one thing different, the while loop while check before doing anything, and the do while will do something then check, this means that the thing you want done will be done once even if the condition is false, but if the condition is false, it will only do it once.

Now to the examples, I will use the trace function in flash, this is kind of a developers eye, an output view port, you type code like this trace("hello world") and your output will be hello world.

for (i = 1; i < 11; i++ {
	trace("my first loop");
}

This loop will output my first loop 10 times. the i++ means you add 1 to the existing i number.

var i = 1
while (i < 11) {
    trace("my second loop");
    i++
}

This will output my second loop 10 times, and every time it has traced the text it will add 1 to the i number while i is less than 11.

var i = 1
do {
    trace("my third loop");
    i++
} while (i<10);

And as I explained before, this will do the same as above, but now even though you start with i = 20, which will not return true to the condition, it will still output my third loop one time, because it first checks when the loop has been through once.

Thats it, I hope you learned some actionscripting from me, from my experience, this topic is what a lot of people takes a long time to understand, even though it so simple when you understand it.



gotoAndCrash says: 2008-04-22

There seems to be a typo in your Do While example. It says : var i = 1; but then in the statement you talk about i starting out equalling 20.

anil says: 2008-02-07

thanks to loops

phil says: 2007-12-13

good explaination of Actionscripts though could you give an example of where they would be used and a tutorial on that thanks