when
The when command picks one of several pieces of script text, before the command parser sees any of it.
Syntax
when ( <expression> ) then
...
[ elsewhen ( <expression> ) then
... ]
[ else
... ]
endwhen
expression compares parameters. The word then is required. when, elsewhen, else and endwhen each stand alone on a line.
What it does
The preprocessor tests the guards in order, takes the branch of the first true one, or the else branch, and passes only that text on. The text of the other branches never reaches the parser. The branch can be a whole sequence of commands or a fragment inside one command’s arguments, such as a list of coordinates.
When James applies it
By the preprocessor, when it is read. The text of a branch not taken is dropped. A when is resolved before the phase of the parser matters, so it is legal anywhere.
Rules James adds
- A construct’s whole structure is checked before any guard is tested, so a malformed construct is dropped whole, with one diagnostic.
- Guards are tried one at a time, in order. A guard after the branch taken is not examined at all, so an undefined parameter there raises nothing.
- A
when,fororwhilenest to 64 levels in all. - A
whennever sits inside anifor holds one.
Diagnostics
- E0306: an
ifscope is inside, or encloses, thewhen. - E0307: the construct and another
for,whenorwhilecross. - E0309: the keyword shares its line with other input.
- E0310: more than 64
when,forandwhileconstructs are open. - E0317: the
thenis missing. - E0319: no
endwhencloses it. - E0203: a guard names a parameter that has no value yet.
- E0221: a guard is not a well-formed expression, for example one that holds a
[ ].
Example
The script tests/corpus/113-elsewhen-selects-branch/input.tg, which make test runs:
para x1 2;
para x2 5;
block
when(%x1.gt.%x2) then
1 3;1 3;1 3;
elsewhen(%x1.lt.%x2) then
1 2;1 2;1 2;
else
1 4;1 4;1 4;
endwhen
1 2 1 2 1 2
endpart
The when is inside the argument list of a block. x1 is 2 and x2 is 5, so the first guard %x1.gt.%x2 is false and the elsewhen guard %x1.lt.%x2 is true. The prep dump shows the block with 1 2;1 2;1 2;, and the else branch is skipped.
See also
- elsewhen, else, endwhen: the rest of the construct.
- if: the form the command parser reads.
- Writing a script: the two control families.