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