if
The if command starts a block of commands that James reads only when its test is true.
Syntax
if ( <expression> ) then
...
[ elseif ( <expression> ) then
... ]
[ else
... ]
endif
expression compares parameters, for example %n.eq.2. The word then is required. if and its elseif, else and endif each stand alone on a line.
What it does
James tests the expression when the command parser reaches the if. If it is true, James reads the commands that follow as if they stood there unconditionally. If it is false, James skips them and tests the next elseif, or takes the else. Only one branch of a construct is ever taken. The commands of a branch that is not taken are not read at all: a para or an include there never takes effect.
When James applies it
By the command parser, when it is read. The branch not taken is skipped. It is legal in any phase: Control, Part or Merge.
Rules James adds
- The command parser evaluates an
ifas it reaches it, in script order, and not before. This is why aparain a false branch does not run, and why%nextsrfand other values a command sets are available to a guard that comes after that command. - A construct holds at most 64 open
iflevels. James reports the 65th and treats it as not opened. - An
ifmust close in the file that opened it. Anifopened in an included file and closed in the file that included it is an error in both files. - An
ifnever sits inside awhen,fororwhile, or holds one, and a control statement shares its line with nothing else. - A guard is evaluated once, so a
randornormin it advances the generator the same way whichever keyword it sits on.
Diagnostics
- E0306: the
ifis inside, or encloses, awhen,fororwhilescope. - E0309: the keyword shares its line with other input.
- E0317: the
thenis missing. - E0319: the
ifis not closed by anendifin the same file. - E0320: more than 64
ifconstructs are open. - 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/132-if-false-branch-inert/input.tg, which make test runs:
if(1.eq.2)then
para x 1;
include missing.inc
sd 9 sp 0 0 0 1
endif
sd [%nextsrf] sp 0 0 0 1
The test 1.eq.2 is false, so James skips lines 2 to 4. The para, the include of a file that does not exist and the sd 9 all do nothing, and James raises no error for the missing file. The last line takes the surface number %nextsrf, which is still 1, so the IR holds one surface with id 1.
See also
- elseif, else, endif: the rest of the construct.
- when: the form that selects text inside a command’s arguments.
- Writing a script: the two control families.