| Chapter 11: Phrases |

| 11.8. Otherwise

We often need code which does one thing in one circumstance, and another the rest of the time. We could do this like so:

> if N is 2 begin; ...; end if;
> if N is not 2 begin; ...; end if;

but this is not very elegant, and besides, what if the action we take when N is 2 changes N so that it becomes something else?

Instead we use "otherwise":

> if N is 2 begin;
> ...;
> otherwise;
> ...;
> end if;

Note that there is only one "end if": the "otherwise" phrase occurs inside the "if ... end if" block of phrases.

When there is only a single phrase we can use the shortened form:

> if N is 2 then say "Hooray, N is 2!";
> otherwise say "Boo, N is not 2..."

Often, though, what we want is to divide up a situation into many cases, and for this the abbreviation "otherwise if" is allowed:

> if N is 1 begin;
> ...;
> otherwise if N is 2;
> ...;
> otherwise if N is greater than 4;
> ...;
> end if;

At most one of the "..." clauses is ever reached - the first which works out. Note that there is only a single "end if", at the end: it all counts as a single "if" construction.

(In almost every computer programming language ever devised, including previous versions of Inform, the word "else" is used rather than "otherwise": for the sake of familiarity, "else" can also be used here. All the same, "otherwise" seems closer to natural English.)

140
| Example Numberless A simple exercise in printing the names of random numbers, using "otherwise if..." and also a table-based alternative. (Or, in programming terms, how to emulate a switch statement.)

> "Numberless" The Rambling Warren is a room. When play begins: let N be a random number between 1 and 5; if N is 1 begin; say "N is one."; otherwise if N is 2; say "N is two."; otherwise if N is 3; say "N is three."; otherwise; say "N is more than the number of your toes."; end if. The final "otherwise" here will fire only if none of the earlier conditions applies; we could leave it out and print nothing in the case that N is 4 or 5. Alternatively, we can use a construction we've seen only briefly before now: a table. The use of tables will be explained more fully in their own chapter, but here we see in brief that we can assign a number of values to one column of a table and then use that table to look up output: When play begins: let X be a random number between 11 and 14; if X is a number listed in the Table of Switching, say "[output entry][paragraph break]"; otherwise say "X is greater than the number of your noses!" Table of Switching
> number | output
> 11 | "X is eleven!"
> 12 | "X is twelve!"
> 13 | "X is thirteen!"
Test me with "z". As we shall see, things other than text can be stored in tables, so we could also use a table as a way to look up objects or even rules to carry out.

Previous | Contents | Next