for

The for command repeats a piece of script text a fixed number of times, with a parameter that counts.

Syntax

for <name> <start> <end> <step>
    ...
endfor

name is the counting parameter. start, end and step are numbers, integers or reals. step is never zero. for and endfor each stand alone on a line.

What it does

The preprocessor repeats the body once for each value name takes, so the parser sees the body as many times as it runs. The loop sets name to start, then adds step each pass. Inside the body %name is the current value. The body can be whole commands or part of one command’s arguments.

When James applies it

By the preprocessor, when it is read. The body is repeated before the parser sees it. A for is resolved before the phase of the parser matters, so it is legal anywhere.

Rules James adds

  • The trip count is fixed once, when the loop opens, as in a Fortran DO loop: MAX(FLOOR((end - start) / step) + 1, 0), in double precision. It is the same whether the three numbers are written as integers or reals.
  • A negative step counts down: for i 10 1 -1 runs 10 passes. Equal bounds give one pass. A step that does not divide the range leaves the last value short of end: for x 0 1 0.3 runs 4 passes, at 0, 0.3, 0.6 and 0.9.
  • A step of zero is an error.
  • A loop that would run more than 1,000,000 passes is an error and runs none.
  • for, when and while nest to 64 levels in all. A for can sit inside the arguments of another command.
  • A for never sits inside an if or holds one, and must close in the file that opened it.

Diagnostics

  • E0307: the loop and another construct cross.
  • E0309: the keyword shares its line with other input.
  • E0310: more than 64 when, for and while constructs are open.
  • E0311: the step is zero.
  • E0312: the loop would run more than 1,000,000 passes.
  • E0319: no endfor closes it.
  • E0205: the counting name is an automatic parameter, as in for pi 1 2 1.
  • E0216: the counting name holds a reserved character, as in for a+b 1 2 1.
  • E0301: raised on a stray endfor, the loop’s closer.
  • E0316: the closer does not match the open construct.

Example

The script tests/corpus/022-for-noninteger-step/input.tg, which make test runs:

for x 0 1 0.3
para y [%x*10];
endfor

The step is 0.3 and the end is 1, so the trip count is 4. The prep dump shows para y four times, with 0, 3, 6 and 9, which are %x*10 at x of 0, 0.3, 0.6 and 0.9.

See also


James 0.3.1.

This site uses Just the Docs, a documentation theme for Jekyll.