Author Topic: How do for() statements work?  (Read 405 times)

How do for statements wori? And what can you do with them?

How do for statements wori? And what can you do with them?
Like this.

Code: [Select]
for($a = 0; $a < 100; $a++)
{
echo($a);
}

And, a lot.


The syntax for a for loop is this:
Code: [Select]
for( On Loop Start; Keep Looping If; In Between Loops)

Usually, for loops are utilized in scanning through a group/list/array.

Code: [Select]
for(%a = 0; %a < ClientGroup.getCount(); %a++)
{
%client = ClientGroup.getObject(%a);
something_to_do_for_this_client(%client);
}


Loops can go inside loops. This goes through each brick in the game by going through each brick group.

Code: [Select]
for(%a = 0; %a < MainBrickGroup.getCount(); %a++)
{
%brickGroup = MainBrickGroup.getObject(%a);

for(%b = 0; %b < %brickGroup.getCount(); %b++)
{
%brick = %brickGroup.getObject(%a);
do_something_for_a_brick(%brick);
}
}

What are you trying to accomplish?

It's also worth noting that the In Between Loops happens at the end of each loop, then the Keep Looping If is checked before starting the next one.

This means that in his first example, after the loop, $a will be 100 but wont echo 100 during the loop. It will echo between 0 and 99.

A for loop like this:
Code: [Select]
for (startStmt; cond; postStmt) { block }

Is syntactical sugar for:
Code: [Select]
startStmt;
while (cond) {
    block
    postStmt;
}

What are you trying to accomplish?
I am not trying to accomplish anything. Although I asked so I could experiment with the for() statement.

Thank you.