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