IF

>>-IF--expression--+---+--THEN--+---+--instruction-------------->
                   +-;-+        +-;-+

>--+--------------------------+--------------------------------><
   +-ELSE--+---+--instruction-+
           +-;-+

IF conditionally processes an instruction or group of instructions depending on the evaluation of the expression. The expression is evaluated and must result in 0 or 1.

The instruction after the THEN is processed only if the result is 1 (true). If you specify an ELSE, the instruction after ELSE is processed only if the result of the evaluation is 0 (false).

Example:

if answer="YES" then say "OK!"
else say "Why not?"

Remember that if the ELSE clause is on the same line as the last clause of the THEN part, you need a semicolon before ELSE.

Example:

if answer="YES" then say "OK!";  else say "Why not?"

ELSE binds to the nearest IF at the same level. You can use the NOP instruction to eliminate errors and possible confusion when IF constructs are nested, as in the following example.

Example:

If answer = "YES" Then
  If name = "FRED" Then
    say "OK, Fred."
  Else
    nop
Else
  say "Why not?"

The expression may also be a list of expressions separated by ",". Each subexpression must evaluate to either 0 or 1. The list of expressions is evaluated left-to-right. Evaluation will stop with the first 0 result and 0 will be returned as the condition result. If all of the subexpressions evaluate to 1, then the condition result is also 1.

Example:

If answer~datatype('w'), answer//2 = 0 Then
  say answer "is even"
Else
  say answer "is odd"

The example above is not the same as using the following

If answer~datatype('w') & answer//2 = 0 Then
  say answer "is even"
Else
  say answer "is odd"

The logical & operator will evaluate both terms of the operation, so the term "answer//2" will result in a syntax error if answer is a non-numeric value. With the list conditional form, evaluation will stop with the first false result, so the "answer//2" term will not be evaluated if the datatype test returns 0.

Notes:

  1. The instruction can be any assignment, message instruction, command, or keyword instruction, including any of the more complex constructs such as DO, LOOP, SELECT, or the IF instruction itself. A null clause is not an instruction, so putting an extra semicolon (or label) after THEN or ELSE is not equivalent to putting a dummy instruction (as it would be in C). The NOP instruction is provided for this purpose.

  2. The symbol THEN cannot be used within expression, because the keyword THEN is treated differently in that it need not start a clause. This allows the expression on the IF clause to be ended by THEN, without a semicolon (;) being required.