User Tools

Site Tools


Sidebar

hpl2:tutorials:script:forloop

"For" Loops

“For” loops are used to repeat some operation multiple times, for example to do something with a variable, or to call an engine function several times in a row. It is almost the same as the “While” loop.

A “for” loop's header defines 3 parts things: (1) the counting variable, set to an initial value, (2) the loop condition, and (3) the change in the variable's value. These are separated by a semicolon ( ; ). After the header, comes the body of the loop, which defines what is it that should be done on each loop cycle (note: a loop cycle is usually called an iteration). It can consist of a single statement, or of multiple statements in a code block.

The structure of a “for” loop:

for (counter; condition; step)
    DoSomething();

Or, with a code block:

for (counter; condition; step)
{
    DoSomething();
    DoSomethingElse();
    WhyNotDoThisToo();
}

Basically, the loop uses the counter variable, checks if the condition is true, executes the loop body if it is, and then changes the counter by the specified step. Then it does it all over again, untill the condition evaluates to false.

There are many different ways you can create “for” loops. Here are some examples:

void OnStart() 
{  	
        for(int i = 0; i <4; i++)
              AddTimer("T" + i, 1.5 * i, "TimerFunction");   
}

Let's take this apart. “void OnStart()” is the location it is in, which happens when the level starts up.

The “for(int i = 0; i < 4; i++)” runs the loop body (in this case, the loop body adds a timer that will trigger “TimerFunction”) 4 times before the loop breaks, because integer “i” has to be less than 4, as stated in the loop condition.

NOTE: It's an old programming tradtion to start your counters from 0 - maybe this seems counter-intuitive, but it's often more convenient to do so. Just remember, if you see the initial value of the counter variable set to 0, and the condition states i < 4, a loop like this will execute 4 times, not 3.
Why? Look at how the value changes: i= 0, 1, 2, 3 , (4 doesn't execute, as the condition is not true for i=4).

If you didn't use the “for” loop, it would look like this:

void OnStart() 
{ 
	AddTimer("T0", 1.5, &

    
                    
                                    
hpl2/tutorials/script/forloop.txt · Last modified: 2012/09/12 13:21 by jens