[AS3] While loop verses For loop

Subscribe to [AS3] While loop verses For loop 8 posts

avatar for I_love_you_lots I_love_you_lots 247 posts
Flag Post

As a preface, I will be unable to respond within reasonable times (as I have no constant internet access.)

Humor me if I’m wrong (me is n00b), but doesn’t a ‘for’ loop create a new variable every time it executes? Even if it’s just an integer, that’s kinda sketchy IMHO.

If that’s true, for loops would be great for single uses (say, loading screens) but it’d be dumb for per-frame use…

Due to said suspicion, I’ve been using ‘while’ loops for a while…heh…anyhow, could someone confirm this for me?

Thanks in advance, and happy Tuesday to all!

 
avatar for Draco18s Draco18s 6860 posts
Flag Post

for(...) loops are for when you have a knowable number of executions. myArray.length for example. (“Do f(x) Y times.”)

While loops are for when the number of executions are less certain:
(“do f(x) while Q is true”)

var r:int = Math.random()*max;
var p:int = Math.random()*max;
while(r == p) {
    p = Math.random()*max;
}

But it’s always possible to use any loop in place of any other loop. If you know what you’re doing.

for loops would be great for single uses (say, loading screens)

What?

 
avatar for truefire truefire 3011 posts
Flag Post

The typical use ( for (var i:int = 0; i < ###; i++){/*stuff*/} ) would create a new variable, but a for loop itself does not necessarily have to.

A for loop of the form:

for (A;B;C) {D;}

is equivalent to

A;
while(B)
{
     D;
     C;
}

The reason it usually creates a new variable is because you explicitly tell it to in A, ie: var i:int = 0;

A,B,C,D can be any statements you want.

 
avatar for BobJanova BobJanova 852 posts
Flag Post
… doesn’t a ‘for’ loop create a new variable every time it executes?

No. A typical for loop of the form
for(var i:int = 0; i < something; i++){ ... }
… declares one variable (i), not one per execution. And you almost always need to assign at the beginning anyway.

 
avatar for NineFiveThree NineFiveThree 1370 posts
Flag Post
Originally posted by I_love_you_lots:

Humor me if I’m wrong (me is n00b), but doesn’t a ‘for’ loop create a new variable every time it executes?

No, not even if you do it within the body of the loop.
http://wiki.joa-ebert.com/index.php/Local_Variables

 
avatar for Senekis93 Senekis93 4090 posts
Flag Post

Both are the same thing; even some decompilers will display all while loops as for ones, as the execution is the same and the decompielr has no way to tell the original syntax.

 
avatar for Draco18s Draco18s 6860 posts
Flag Post
Originally posted by Senekis93:

Both are the same thing; even some decompilers will display all while loops as for ones, as the execution is the same and the decompielr has no way to tell the original syntax.

Vice-versa, usually.
(Displaying for loops as whiles)

 
avatar for I_love_you_lots I_love_you_lots 247 posts
Flag Post

Cool! For loops are cooler! Thanks guys =]