Mention in README.md the need for the iftex package and how to get it.
[ibg.git] / appendices / e.rst
1 ===============================
2  Appendix E -- Inform language
3 ===============================
4
5 .. default-role:: samp
6
7 .. only:: html
8
9    .. image:: /images/picR.png
10       :align: left
11
12 |R|\efer to this appendix for a succinct but essentially complete summary
13 of the Inform programming language; it covers everything that we've met in
14 this guide, plus various constructs which didn't occur naturally, and
15 others of an advanced or obscure nature.
16
17 Literals
18 ========
19
20 In the specialised language of computing, the basic unit of data storage is
21 an eight-bit **byte**, able to store a value 0..255.  That's too small to
22 be useful for holding anything other than a single character, so most
23 computers also work with a group of two, four or eight bytes known as a
24 **word** (not to be confused with Inform's dictionary word).  In the
25 Z-machine a storage word comprises two bytes, and you can specify in
26 various ways the literal values to be stored.
27
28 :Decimal: `-32768` to `32767`
29 :Hexadecimal: `$0` to `$FFFF`
30 :Binary: `$$0` to `$$1111111111111111`
31 :Action: `##Look`
32 :Character: `'a'`
33 :Dictionary word: `'aardvark'` (up to nine characters significant); use
34    circumflex "^" to denote apostrophe.
35
36 :Plural word: `'aardvarks//p'`
37
38 :Single-character word: `"a"` (`name` property only) or `'a//'`
39 :String: `"aardvark's adventure"` (maximum around 4000 characters); can
40    include special values including:
41
42      =============   ====================================
43      `^`             newline
44      `~`             double quotes "`\"`"
45      `@@64`          at sign "`@`"
46      `@@92`          backslash "`\\`"
47      `@@94`          circumflex "`^`"
48      `@@126`         tilde "`~`"
49      `@\`a`          a with a grave accent "`à`", et al
50      `@LL`           pound sign "`£`", et al
51      `@00 ... @31`   low string 0..31
52      =============   ====================================
53
54 Names
55 =====
56
57 The identifier of an Inform `{const_id}`, `{var_id}`, `{array}`,
58 `{class_id}`, `{obj_id}`, `{property}`, `{attribute}`, `{routine_id}` or
59 `{label}`.  Up to 32 characters: alphabetic (case not significant), numeric
60 and underscore, with the first character not a digit.
61
62 Constants
63 =========
64
65 Named word values, unchanging at run-time, which are by default initialised
66 to zero:
67
68   | `Constant {const_id}`;
69   | `Constant {const_id} = {expr}`;
70
71 .. Generated by autoindex
72 .. index::
73    pair: NULL; library constant
74    pair: false; library constant
75    pair: nothing; library constant
76    pair: true; library constant
77
78 Standard constants are :const:`true` (1), :const:`false` (0) and
79 :const:`nothing` (0), also :const:`NULL` (-1).  Additionally, `WORDSIZE` is
80 the number of bytes in a storage word: 2 for the Z-machine, 4 for Glulx.
81
82 To define a constant (unless it already exists):
83
84   | `Default {const_id expr}`;
85
86 Variables and arrays
87 ====================
88
89 Named word/byte values which can change at run-time and are by default
90 initialised to zero.
91
92 A **global** variable is a single word:
93
94   | `Global {var_id}`;
95   | `Global {var_id} = {expr}`;
96
97 A **word array** is a set of global words accessed using
98 `{array}->0,{array}->1,... {array}->({N}-1)`:
99
100   | `Array {array} --> {N};`
101   | `Array {array} --> {expr1 expr2... exprN};`
102   | `Array {array} --> "{string}";`
103
104 A **table array** is a set of global words accessed using `{array}->1,
105 {array}->2,... {array}->{N}`, with `{array}->0` initialised to `{N}`:
106
107   | `Array {array} table {N};`
108   | `Array {array} table {expr1... exprN};`
109   | `Array {array} table "{string}";`
110
111 A **byte array** is a set of global bytes accessed using `{array}->0,
112 {array}->1,... {array}->({N}-1)`:
113
114   | `Array {array} -> {N};`
115   | `Array {array} -> {expr1 expr2... exprN};`
116   | `Array {array} -> "{string}";`
117
118 A **string array** is a set of global bytes accessed using `array->1,
119 array->2,... array->{N}`, with `array->0` initialised to `{N}`:
120
121   | `Array {array} string {N};`
122   | `Array {array} string {expr1... exprN};`
123   | `Array {array} string "{string}";`
124
125 A **buffer array** is a set of global bytes accessed using
126 `{array}->(WORDSIZE), {array}->(WORDSIZE+1), ...
127 {array}->(WORDSIZE+{N}-1)`, with the first **word** `{array}->0`
128 initialised to `{N}`:
129
130   | `Array {array} buffer {N};`
131   | `Array {array} buffer {expr1... exprN};`
132   | `Array {array} buffer "{string}";`
133
134 In all these cases, the characters of the initialising `{string}` are
135 unpacked to the individual word/byte elements of the array.
136
137 See also Objects (for **property** variables) and Routines (for **local**
138 variables).
139
140 Expressions and operators
141 =========================
142
143 Use parentheses `(...)` to control the order of evaluation.
144
145 Arithmetic/logical expressions support these operators:
146
147   ===========        ====================================
148   `{p} + {q}`        addition
149   `{p} - {q}`        subtraction
150   `{p} * {q}`        multiplication
151   `{p} / {q}`        integer division
152   `{p} % {q}`        remainder
153   `{p}++`            increments `{p}`, returns orig value
154   `++{p}`            increments `{p}`, returns new value
155   `{p}--`            decrements `{p}`, returns orig value
156   `--{p}`            decrements `{p}`, returns new value
157   `{p} & {q}`        bitwise AND
158   `{p} | {q}`        bitwise OR
159   `~{p}`             bitwise NOT (inversion)
160   ===========        ====================================
161
162 Conditional expressions return `true` or `false`; `{q}` may be a list of
163 choices `{q1} or {q2} or ... {qN}`:
164
165   ==================   ==========================================
166   `{p} == {q}`         `{p}` is equal to `{q}`
167   `{p} ~= {q}`         `{p}` isn't equal to `{q}`
168   `{p} > {q}`          `{p}` is greater than `{q}`
169   `{p} < {q}`          `{p}` is less than `{q}`
170   `{p} >= {q}`         `{p}` is greater than or equal to `{q}`
171   `{p} <= {q}`         `{p}` is less than or equal to `{q}`
172   `{p} ofclass {q}`    object `{p}` is of class `{q}`
173   `{p} in {q}`         object `{p}` is a child of object `{q}`
174   `{p} notin {q}`      object `{p}` isn't a child of object `{q}`
175   `{p} provides {q}`   object `{p}` provides property `{q}`
176   `{p} has {q}`        object `{p}` has attribute `{q}`
177   `{p} hasnt {q}`      object `{p}` hasn't attribute `{q}`
178   ==================   ==========================================
179
180 Boolean expressions return `true` or `false`; if `{p}` has determined the
181 result, `{q}` is not evaluated:
182
183   ============   ========================================
184   `{p} && {q}`   both `{p}` and `{q}` are true (non-zero)
185   `{p} || {q}`   either `{p}` or `{q}` is true (non-zero)
186   `~~{p}`        `{p}` is false (zero)
187   ============   ========================================
188
189 To return -1, 0 or 1 based on unsigned comparison:
190
191     | `UnsignedCompare({p},{q})`
192
193 To return `true` if object `{q}` is a child or grandchild or... of `{p}`:
194
195     | `IndirectlyContains({p},{q})`
196
197 To return the closest common parent of two objects (or nothing):
198
199     | `CommonAncestor({p},{q})`
200
201 To return a random number `1..{N}`, or one from a list of constant values:
202
203     | `random({N})`
204     | `random({value,value, ... value})`
205
206 Classes and objects
207 ===================
208
209 To declare a `{class_id}` - a template for a family of objects - where the
210 optional (`{N}`) limits instances created at run-time:
211
212   | `Class {class_id}({N})`
213   |  `class {class_id} {class_id}... {class_id}`
214   |  `with {prop_def},`
215   |        `...`
216   |        `{prop_def},`
217   |  `has   {attr_def} {attr_def}... {attr_def};`
218
219 To declare an `{obj_id}`, "`Object`" can instead be a `{class_id}`, the
220 remaining four header items are all optional, and `{arrows}` (`->`, `->
221 ->`, ...)  and `{parent_obj_id}` are incompatible:
222
223   | `Object {arrows obj_id} "{ext_name}" {parent_obj_id}`
224   |  `class {class_id} {class_id}... {class_id}`
225   |  `with {prop_def},`
226   |         `...`
227   |         `{prop_def},`
228   |  `has    {attr_def} {attr_def}... {attr_def};`
229
230 The `class`, `with` and `has` (and also the rarely-used `private`) segments
231 are all optional, and can appear in any order.
232
233 To determine an object's class as one of `Class`, `Object`, `Routine`,
234 `String` (or `nothing`):
235
236   | `metaclass({obj_id})`
237
238 **has segment**: Each `{attr_def}` is either of:
239
240   | `{attribute}`
241   | `~{attribute}`
242
243 To change attributes at run-time:
244
245   | `give {obj_id attr_def... attr_def};`
246
247 **with/private segments**: Each `{prop_def}` declares a variable (or word
248 array) and can take any of these forms (where a `{value}` is an expression,
249 a string or an embedded routine):
250
251   | `{property}`
252   | `{property value}`
253   | `{property value value... value}`
254
255 A property variable is addressed by `{obj_id.property}` (or within the
256 object's declaration as `{self.property}`).
257
258 Multiple `{values}` create a property array; in this case
259 `{obj_id.#property}` is the number of bytes occupied by the array, the
260 entries can be accessed using `{obj_id.&property}-->0`,
261 `{obj_id.&property}->1`, ..., and `{obj_id.property}` refers to the value
262 of the first entry.
263
264 A property variable inherited from an object's class is addressed by
265 `{obj_id.class_id}::{property}`; this gives the original value prior to any
266 changes within the object.
267
268 Manipulating the object tree
269 ============================
270
271 To change object relationships at run-time:
272
273   | `move {obj_id} to {parent_obj_id};`
274   | `remove {obj_id};`
275
276 To return the parent of an object (or nothing):
277
278   | `parent({obj_id})`
279
280 To return the first child of an object (or nothing):
281
282   | `child({obj_id})`
283
284 To return the adjacent child of an object's parent (or nothing):
285
286   | `sibling({obj_id})`
287
288 To return the number of child objects directly below an object:
289
290   | `children({obj_id})`
291
292 Message passing
293 ===============
294
295 To a class:
296
297   | `{class_id}.remaining()`
298   | `{class_id}.create()`
299   | `{class_id}.destroy({obj_id})`
300   | `{class_id}.recreate({obj_id})`
301   | `{class_id}.copy({to_obj_id},{from_obj_id})`
302
303 To an object:
304
305   | `{obj_id.property(a1,a2, ... a7)}`
306
307 To a routine:
308
309   | `{routine_id}.call({a1,a2, ... a7})`
310
311 To a string:
312
313   | `{string}.print()`
314   | `{string}.print_to_array({array})`
315
316 Uncommon and deprecated statements
317 ==================================
318
319 To jump to a labelled statement:
320
321   | `jump {label};`
322   | `...`
323   | `.{label}; {statement};`
324
325 To terminate the program:
326
327   | `quit;`
328
329 To save and restore the program state:
330
331   | `save {label};`
332   | `...`
333   | `restore {label};`
334
335 To output the Inform compiler version number:
336
337   | `inversion;`
338
339 To accept data from the current input stream:
340
341   | `read {text_array parse_array routine_id};`
342
343 To assign to one of 32 'low string' variables:
344
345   | `string {N} "{string}";`
346   | `Lowstring {string_var} "{string}";`
347   | `string {N string_var};`
348
349 Statements
350 ==========
351
352 Each `{statement}` is terminated by a semicolon "`;`".
353
354 A `{statement_block}` is a single `{statement}` or a series of
355 `{statements}` enclosed in braces ``{...}``.
356
357 An exclamation "`!`" starts a comment - the rest of the line is ignored.
358
359 A common statement is the assignment:
360
361   | `{var_id} = {expr};`
362
363 There are two forms of multiple assignment:
364
365   | `{var_id} = {var_id} = ... = {expr};`
366   | `{var_id} = {expr}, {var_id} = {expr}, ... ;`
367
368 Routines
369 ========
370
371 A routine can have up to 15 **local variables**: word values which are
372 private to the routine and which by default are set to zero on each call.
373
374 Recursion is permitted.
375
376 A **standalone** routine:
377
378 * has a name, by which it is called using `{routine_id}();` can also be
379   called indirectly using `indirect({routine_id,a1,a2, ... a7})`
380
381 * can take arguments, using `{routine_id}({a1,a2, ... a7})`, whose values
382   initialise the equivalent local variables
383
384 * returns `true` at the final "`]`"
385
386   | `[ {routine_id}`
387   |     `{local_var} {local_var}... {local_var};`
388   |     `{statement};`
389   |     `{statement};`
390   |     `...`
391   |     `{statement};`
392   | `];`
393
394 A routine **embedded** as the value of an object property:
395
396 * has no name, and is called when the property is invoked; can also be
397   called explicitly using `{obj_id.property}()`
398
399 * accepts arguments only when called explicitly
400
401 * returns `false` at the final "`]`"
402
403   | `property [`
404   |     `{local_var} {local_var}... {local_var};`
405   |     `{statement};`
406   |     `{statement};`
407   |     `...`
408   |     `{statement};`
409   | `]`
410
411 Routines return a single value, when execution reaches the final "`]`" or
412 an explicit `return` statement:
413
414   | `return {expr};`
415   | `return;`
416   | `rtrue;`
417   | `rfalse;`
418
419 Flow control
420 ============
421
422 To execute statements if `{expr}` is `true`; optionally, to execute other
423 statements if `{expr}` is `false`:
424
425   | `if ({expr})`
426   |     `{statement_block}`
427   |
428   | `if ({expr})`
429   |     `{statement_block}`
430   | `else`
431   |     `{statement_block}`
432
433 To execute statements depending on the value of `{expr}`:
434
435   | `switch ({expr}) {`
436   |     `{value}: {statement};... {statement};`
437   |     `{value}: {statement};... {statement};`
438   |     `...`
439   |     `default: {statement};... {statement};`
440   | `}`
441
442 where each `{value}` can be given as:
443
444   | `{constant}`
445   | `{lo_constant} to {hi_constant}`
446   | `{constant,constant,... constant}`
447
448 And, if you really must:
449
450   | `jump {label};`
451   | `...`
452   | `.{label}; {statement};`
453
454 Loop control
455 ============
456
457 To execute statements while `{expr}` is true:
458
459   | `while ({expr})`
460   |     `{statement_block}`
461
462 To execute statements until `{expr}` is true:
463
464   | `do`
465   |      `{statement_block}`
466   |      `until ({expr})`
467
468 To execute statements while a variable changes:
469
470   | `for ({set_var} : {loop_while_expr} : {update_var})`
471   |     `{statement_block}`
472
473 To execute statements for all defined objects:
474
475   | `objectloop ({var_id})`
476   |     `{statement_block}`
477
478 To execute statements for all objects selected by `{expr}`:
479
480   | `objectloop ({expr_starting_with_var})`
481   |     `{statement_block}`
482
483 To jump out of the current innermost loop or switch:
484
485   | `break;`
486
487 To immediately start the next iteration of the current loop:
488
489   | `continue;`
490
491 Displaying information
492 ======================
493
494 To output a list of values:
495
496   | `print {value},{value},... {value};`
497
498 To output a list of values followed by a newline, then return `true` from
499 the current routine:
500
501   | `print_ret {value},{value},... {value};`
502
503 If the first (or only) `{value}` is a string, "`print_ret`" can be
504 omitted:
505
506   | `"{string}",{value}, ... {value};`
507
508 Each `{value}` can be an expression, a string or a rule.
509
510 An **expression** is output as a signed decimal value.
511
512 A **string** in quotes "`...`" is output as text.
513
514 A **rule** is one of:
515
516   ========================    ===============================================
517   `(number) {expr}`           the `{expr}` in words
518   `(char) {expr}`             the `{expr}` as a single character
519   `(string) {addr}`           the string at the `{addr}`
520   `(address) {addr}`          the dictionary word at the `{addr}`
521   `(name) {obj_id}`           the external (short) name of the `{obj_id}`
522   `(a) {obj_id}`              the short name preceded by "`a/an`",
523                               by "`some`", or by nothing for proper nouns
524   `(A) {obj_id}`              the short name preceded by "`A/An`",
525                               by "`Some`", or by nothing for proper nouns
526   `(the) {obj_id}`            the short name preceded by "`the`"
527   `(The) {obj_id}`            the short name preceded by "`The`"
528   `({routine_id}){value}`     the output when calling `{routine_id}({value})`
529   ========================    ===============================================
530
531 To output a newline character:
532
533   | `new_line;`
534
535 To output multiple spaces:
536
537   | `spaces {expr};`
538
539 To output text in a display box:
540
541   | `box "{string}" "{string}"... "{string}";`
542
543 To change from regular to fixed-pitch font:
544
545   | `font off;`
546   | `...`
547   | `font on;`
548
549 To change the font attributes:
550
551   | `style bold;          ! use any of these`
552   | `style underline;     !`
553   | `style reverse;       !`
554   | `...`
555   | `style roman;`
556
557 Verbs and actions
558 =================
559
560 To specify a new verb:
561
562   | `Verb '{verb}' '{verb}'... '{verb}'`
563   |   `* {token} {token}... {token} -> {action}`
564   |   `* {token} {token}... {token} -> {action}`
565   |   `...`
566   |   `* {token} {token}... {token} -> {action}`
567
568 where instead "`Verb`" can be "`Verb meta`", "`{action}`" can be "`{action
569 reverse}`"; `{tokens}` are optional and each is one of:
570
571   ====================   ==================================================
572   `'{word}'`             that literal word
573   `'{w1}'/'{w2}'/...`    any one of those literal words
574   `{attribute}`          an object with that attribute
575   `creature`             an object with `animate` attribute
576   `held`                 an object held by the player
577   `noun`                 an object in scope
578   `noun={routine_id}`    an object for which `{routine_id}` returns `true`
579   `scope={routine_id}`   an object in this re-definition of scope
580   `multiheld`            one or more objects held by the player
581   `multi`                one or more objects in scope
582   `multiexcept`          as `multi`, omitting the specified object
583   `multiinside`          as `multi`, omitting those in specified object
584   `topic`                any text
585   `number`               any number
586   `{routine_id}`         a general parsing routine
587   ====================   ==================================================
588
589 To add synonyms to an existing verb:
590
591   | `Verb '{verb}' '{verb}'... =`
592   |     `'{existing_verb}';`
593
594 To modify an existing verb:
595
596   | `Extend '{existing_verb}' last`
597   |   `* {token} {token}... {token} -> {action}`
598   |   `* {token} {token}... {token} -> {action}`
599   |   `...`
600   |   `* {token} {token}... {token} -> {action}`
601
602 where instead "`Extend`" can be "`Extend only`" and "`last`" can be
603 omitted, or changed to "`first`" or "`replace`".
604
605 To explicitly trigger a defined action (both `{noun}` and `{second}` are
606 optional, depending on the `{action}`):
607
608   | `<{action noun second}>;`
609
610 To explicitly trigger a defined action, then return `true` from the current
611 routine:
612
613   | `<<{action noun second}>>;`
614
615 Other useful directives
616 =======================
617
618 To set compiler switches *at the very start* of the source file:
619
620   | `!% {list_of_compiler_switches};`
621
622 To include a directive within a routine definition `[...]`, insert a hash
623 "`#`" as its first character.
624
625 To conditionally compile:
626
627   | `Ifdef {name};       ! use any one of these`
628   | `Ifndef {name};      !`
629   | `Iftrue {expr};      !`
630   | `Iffalse {expr};     !`
631   |    `...`
632   | `Ifnot;`
633   |    `...`
634   | `Endif;`
635
636 To display a compile-time message:
637
638   | `Message "{string}";`
639
640 To include the contents of a file, searching the Library path:
641
642   | `Include "{source_file}";`
643
644 To include the contents of a file in the same location as the current
645 file:
646
647   | `Include ">{source_file}";`
648
649 To specify that a library routine is to be replaced:
650
651   | `Replace {routine_id};`
652
653 To set the game's release number (default is 1), serial number (default is
654 today's `{yymmdd}`) and status line format (default is `score`):
655
656   | `Release {expr};`
657   | `Serial "{yymmdd}";`
658   | `Statusline score;`
659   | `Statusline time;`
660
661 To declare a new attribute common to all objects:
662
663   | `Attribute {attribute};`
664
665 To declare a new property common to all objects:
666
667   | `Property {property};`
668   | `Property {property expr};`
669
670 Uncommon and deprecated directives
671 ==================================
672
673 You're unlikely to need these; look them up in the |DM4| if necessary.
674
675   | `Abbreviate "{string}"... "{string}";`
676   | `End;`
677   | `Import {var_id var_id} ... {var_id};`
678   | `Link "{compiled_file}";`
679   | `Stub {routine_id N};`
680   | `Switches {list_of_compiler_switches};`
681   | `System_file;`