Next: , Previous: Allocation macros, Up: Programming definitions


7.3 Iteration

You can iterate through a comma-separated list of items with \for. Here is an example:

     \for\name:=karl,kathy\do{%
        \message{\name}%
     }%

This writes ‘karl’ and ‘kathy’ to the terminal. Spaces before or after the commas in the list, or after the :=, are not ignored. To strip leading spaces off the items, use \For:

     \For\name:=
        karl,
        kathy\do{%
           \message{\name}%
        }%

Note that trailing spaces are still not ignored.

Both \for and \For expand the first token of the item list fully, so this is equivalent to the above:

     \def\namelist{karl,kathy}%
     \for\name:=\namelist\do ...

However, this won't work, either with \for or with \For:

     \def\namelist{karl,kathy}%
     \For\name:= \namelist\do ...

because \for and \For expand the first token after := which is space, not \namelist.

Eplain provides another kind of loops, which is an extension of plain TeX's \loop. If you say:

     \loop
       loop-text
     \if condition
       if-text
     \repeat

then loop-text will be repeated as long as condition is satisfied (\if can be any of the TeX's conditional commands, without the matching \fi). Eplain extends this with the optional else clause:

     \loop
       loop-text
     \if condition
       if-text
     \else
       else-text
     \repeat

Here, loop-text will be repeated as long as condition is not satisfied. This extension is from Victor Eijkhout's TeX by Topic (page 104).