Author Topic: What exactly does for() do?  (Read 984 times)

for(%a = 0; %a < %obj.getDatablock().maxTools; %a++)
I think this means %a is increaser for every item slots there are, but honestly I have no idea.
Can someone describe in-depth what this does?

In parts:
(1) set %a to zero
(2) run code in the "body" of the loop until %a is greater than the max tools
(3) add 1 to %a
« Last Edit: July 11, 2013, 11:16:21 PM by Kalphiter² »

Then couldn't you just do while(%a < %obj.getDatablock().maxTools) {%a++;} ?

Yes, it is the same but a for loop is better-purposed for that situation.

You should set %a to zero first, however.

for(initialization;loopstart/conditional;loopend)
{
    code;
}

initialization;
while(loopstart/conditional)
{
   code;
   loopend;
}

The only difference between these two1 is that for the while loop, using "continue;" would make the loopend part not run.


for(%i=0;%i<10;%i++)   //Echoes 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9
{
    echo(%i);
    continue;
}

%i = 0;
while(%i < 10)   //Echoes 0 in an infinite loop. Freezes your game2.
{
    echo(%i);
    continue;
    %i++;
}


1As far as I know/remember at this time.
2That code simplifies to while(true) { echo(%i); } due to the continue;.

Then couldn't you just do while(%a < %obj.getDatablock().maxTools) {%a++;} ?

Generally when you are deciding whether you want to use a while loop or a for loop, you use a for loop when it matters what iteration you are on or if you have a specific number of times you want something looped, and a while loop otherwise.
For example, using a variable that counts the number of loops, then accesses a different variable in an array, (such as $var[0], $var[1], $var[2] with just $var[%i]) is perfect in a for loop.
If you just want to call some function repeatedly until it returns a certain value, a while loop is more efficient.

Code: [Select]
while(%dragon.isAlive())
{
     %warrior.heal();
     %warrior.dodge();
     %warrior.attack(%dragon);
}

There really isn't any situation that you absolutely need to use a for loop or absolutely need to use a while loop, but each are optimized for different things.

(2) run code in the "body" of the loop until %a is greater than or equal to the max tools

Come on. Comparisons are simple.

Come on. Comparisons are simple.
Mistakes like that happen when wording is reversed but the entire sentence isn't fixed. Calm your titties.

Come on. Comparisons are simple.
Wait, what?
If it's only called when %a is LESS than %obj.getDatablock().maxTools, wouldn't that mean it stops when it's equal?

Wait, what?
If it's only called when %a is LESS than %obj.getDatablock().maxTools, wouldn't that mean it stops when it's equal?

That's what I said, yeah.

That's what I said, yeah.
So your bold text was a correction rather than a highlight, okay.