Yorick: if-else constructs

Home Manual Packages Global Index Keywords Quick Reference |
#### 1.2.3.1 General `if` and `else` constructs The most general form of the `if` statement is:
    if (condition) statement_if_true;
    else statement_if_false;
When you need to choose among several alternatives, make the `else` clause itself an `if` statement:
    if (condition_1) statement_if_1;
    else if (condition_2) statement_if_2;
    else if (condition_3) statement_if_3;
    ...
    else statement_if_none;
The final `else` is always optional -- if it is not present, nothing at all happens if none of the conditions is satisfied. Often you need to execute more than one statement conditionally. Quite generally in Yorick, you may group several statements into a single compound statement by means of curly braces:
    { statement_1; statement_2; statement_3; statement_4; }
Ordinarily, both curly braces and each of the statements should be written on a separate line, with the statements indented to make their membership in the compound more obvious. Further, in an if-else construction, when one branch requires more than one statement, you should write every branch as a compound statement with curly braces. Therefore, for a four branch `if` in which the second `if` requires two statements, and the `else` three, write this:
    if (condition_1) {
      statement_if_1;
    } else if (condition_2) {
      statement_if_2_A;
      statement_if_2_B;
    } else if (condition_3) {
      statement_if_3;
    } else {
      statement_if_none_A;
      statement_if_none_B;
      statement_if_none_C;
    }
The `else` statement has a very unusual syntax: It is the only statement in Yorick which depends on the form of the previous statement; an `else` must follow an `if`. Because Yorick statements outside functions (and compound statements) are executed immediately, you must be very careful using `else` in such a situation. If the `if` has already been executed (as it would be in the examples without curly braces), the following `else` leads to a syntax error! The best way to avoid this puzzling problem is to always use the curly brace syntax of the latest example when you use `else` outside a function. (You don't often need it in such a context anyway.)