The for statement has the following syntax:
for variable = from_exp , to_exp [, step_exp] do
block
end
The statement sets the value of the variable to from_exp before entering the for block. The block is only entered if the variable has not passed the last value, to_exp. This includes the first time the loop is iterated over. Each time the block exits, step_exp is added to variable. Specifying the step expression is optional. If it is not specified, a value of 1 is used. For example:
> for i = 1,3 do
print(i,"\n")
end // count from 1 to 3
1
2
3
> for i = 3,1 do // count from 3 to 1 in steps of 1. zero iterations!
print(i)
end
> for i = 3,1,-1 do
print(i,"\n")
end // count down from 3 to 1
3
2
1
> for i=1,0,-0.25 do // Non-integer increments are allowed
print(i,"\n")
end
1
0.75
0.5
0.25
0
> for i=1,0,-0.25 do // Non-integer increments are allowed
print(i,"\n")
end
print(i) // executed after the above code
1
0.75
0.5
0.25
0
0
HyperMath supports another syntax for the for-statement that is akin to C-programming style. The two formats cannot be mixed.
for(initialization; conditional; step)
{
block
}
Any of the expression's initialization, conditional, or step fields may be empty. The initialization code executes once at the very beginning. conditional is tested before each iteration (if it evaluates to false at the beginning, the statement never executes). At the end of each loop, step executes.
Some of the above can be written as follows, per this syntax:
> for(i=0; i<=3; i=i+1)
{
print(i,"\n")
}
0
1
2
3
> for(i=3; i>=1; i=i-1)
{
print(i,"\n")
}
3
2
1
The break statement can be used to terminate a for loop.