Main Index : Reference :

for


Description

Allows easy coding of incrementing loops.

Usage

for (initiation; expression; incrementation)
{
  // Do stuff
}

Program Structure

A for structure repeats a code block as long as expression is true. (A true expression is an expression that's not 0 or nil.) The loop ends when expression is false. This is similar to the while structure, but there are also two other "parameters". The intiation statement is exectuted before the loop starts. The incrementation statement is executed after each loop, before the evaluation of expression.

for loops are most commonly used to create a loop where a certain variable is incremented for each loop until it reaches a certain value. This for loop

var i;

for (i=0; i<10; i++)
{
  // Do stuff
}
is the same as this while loop:
var i = 0;

while (i<10)
{
  // Do stuff
  i++;
}

The syntax i++ means that the variable i is increased by one. It is the same as i+=1 or i=i+1.

If the code to be executed is only one line, one doesn't have to include the enclosing braces, {}.

The expression often consists of comparison operators, such as ==, !=, >, >=, < and <=. These can in turn be combined with logical operators, such as &&, ! and ||. You can read more about these operators here.

Example

// This loop will run ten times, during which 
// the variable i will go from 0 to 9. The 
// output will be "1+2+...+9 = 45".

var i,sum=0;

for (i=0; i<10; i++) 
{
  sum += i; // Increase sum by i
}

println("1+2+...+9 =",sum);


// A for loop is often the base of any code dealing with
// polygons or points, as they are indexed. Here is an
// example:

var i,p,pointcount = obj->GetPointCount();

for (i=0; i<pointcount; i++)
{
  p = obj->GetPoint(i);
  
  // Do something with p
  
  obj->SetPoint(i,p);
}

// Of course, for loops can be used for other things than
// just increasing a variable each loop. This, somewhat
// awkward, code finds the last item in a linked list.

var temp,lastItem;

for (temp=list->GetFirst(); temp; temp=temp->GetNext())
  lastItem = temp;

See Also

Operators