~ubuntu-branches/ubuntu/hoary/inform/hoary

« back to all changes in this revision

Viewing changes to info/inform-2

  • Committer: Bazaar Package Importer
  • Author(s): Mark Baker
  • Date: 2004-03-29 23:52:44 UTC
  • Revision ID: james.westby@ubuntu.com-20040329235244-fox1z1yv7d6vojoo
Tags: upstream-6.30
ImportĀ upstreamĀ versionĀ 6.30

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
This is Info file inform.info, produced by Makeinfo-1.64 from the input
 
2
file inform.texi.
 
3
 
 
4
This is the Inform Designer's Manual, third edition, 4 September 1996,
 
5
as updated 16 May 1997.  It was converted to Info by Christopher J.
 
6
Madsen <ac608@yfn.ysu.edu>.
 
7
 
 
8
Copyright 1996,1997 Graham Nelson and Christopher J. Madsen
 
9
 
 
10
Permission is granted to make and distribute copies of this manual
 
11
provided that:
 
12
 (a) distributed copies are not substantially different from those
 
13
     archived by the author,
 
14
 (b) this and other copyright messages are always retained in full, and
 
15
 (c) no profit is involved.
 
16
 
 
17
 
 
18
File: inform,  Node: Code Blocks,  Next: Loops,  Prev: Example 4,  Up: Routines
 
19
 
 
20
Code blocks, else and switch
 
21
----------------------------
 
22
 
 
23
   A feature of all control constructs is that instead of just giving a
 
24
<statement>, one can give a list of statements grouped together into a
 
25
unit called a "code block".  Such a group begins with an open brace {
 
26
and ends with a close brace }.  For example,
 
27
 
 
28
    if (alpha > 5)
 
29
    {   print "The square of alpha is ";
 
30
        print alpha*alpha;
 
31
        print ".^";
 
32
    }
 
33
 
 
34
If alpha is 3, nothing is printed; if alpha is 9,
 
35
 
 
36
         The square of alpha is 81.
 
37
 
 
38
is printed.  (As usual the layout is a matter of convention: it is
 
39
usual to write code blocks on margins indented inwards by some standard
 
40
number of characters.)  In some ways, code blocks are like routines,
 
41
and at first it may seem inconsistent to write routines between [ and ]
 
42
brackets and code blocks between braces { and }.  However, code blocks
 
43
cannot have private variables of their own and do not return values:
 
44
and it is possible for execution to break out of code blocks again, or
 
45
to jump from block to block, which is impossible with routines.
 
46
 
 
47
   An if statement can optionally have the form
 
48
 
 
49
         if (<condition>) <statement1> else <statement2>
 
50
 
 
51
in which case <statement1> is executed if the condition is true, and
 
52
<statement2> if it is false.  For example,
 
53
 
 
54
    if (alpha == 5) print "Five."; else print "Not five.";
 
55
 
 
56
Note that the condition is only checked once.  The statement
 
57
 
 
58
    if (alpha == 5)
 
59
    {   print "Five.";
 
60
        alpha = 10;
 
61
    }
 
62
    else print "Not five.";
 
63
 
 
64
cannot ever print both "Five" and then "Not five".
 
65
 
 
66
   The else clause has a snag attached: the problem of "hanging elses".
 
67
 
 
68
    if (alpha == 1)
 
69
        if (beta == 2)
 
70
            print "Clearly if alpha=1 and beta=2.^";
 
71
        else
 
72
            print "Ambiguous.^";
 
73
 
 
74
is ambiguous as to which if statement the else attaches to.  The answer
 
75
(in Inform 6, though this has changed since earlier versions of the
 
76
language) is that an else always pairs to its nearest if, unless there
 
77
is bracing to indicate the contrary.  Thus the else above pairs with
 
78
the beta condition, not the alpha condition.
 
79
 
 
80
   In any case it is much safer to use braces to express what is meant,
 
81
as in:
 
82
 
 
83
    if (alpha == 1)
 
84
    {   if (beta == 2)
 
85
            print "Clearly if alpha=1 and beta=2.^";
 
86
        else
 
87
            print "Clearly if alpha=1 but beta not 2.^";
 
88
    }
 
89
 
 
90
The if...else... construct is ideal for switching execution between two
 
91
possible "tracks", like railway signals, but it is a nuisance trying to
 
92
divide between many different outcomes this way.  To follow the
 
93
analogy, the construct switch is like a railway turntable.
 
94
 
 
95
    print "The train on platform 1 is going to ";
 
96
    switch(DestinationOnPlatform(1))
 
97
    {   1: print "Dover Priory.";
 
98
        2: print "Bristol Parkway.";
 
99
        3: print "Edinburgh Waverley.";
 
100
    }
 
101
 
 
102
Each possible value must be a constant, so
 
103
 
 
104
    switch(alpha)
 
105
    {   beta: print "The variables alpha and beta are equal!";
 
106
    }
 
107
 
 
108
is illegal.
 
109
 
 
110
   Any number of outcomes can be specified, and values can be grouped
 
111
together to a common outcome.  For example,
 
112
 
 
113
    print "The mission STS-", num, " was flown on the Space Shuttle";
 
114
    switch(num)
 
115
    {   1 to 5, 9: print " Columbia.";
 
116
        6 to 8:    print " Challenger.";
 
117
        10 to 25:  if (num == 12) print " Discovery";
 
118
                   print ", but it was given a flight number like 51-B.";
 
119
        default:   print ".";
 
120
    }
 
121
 
 
122
will result in a true statement being printed (as long as num is
 
123
between 1 and, at time of writing, 78), if an incomplete one.  The
 
124
default clause is executed if the original expression matches none of
 
125
the other values, and it must always come last if given at all.  In
 
126
this case, it means that if num is 62, then
 
127
 
 
128
         The mission STS-62 was flown on the Space Shuttle.
 
129
 
 
130
is printed.
 
131
 
 
132
   Note that each clause is automatically a code block and needs no
 
133
braces { to } to delimit it from the rest of the routine: this
 
134
shorthand makes switch statements much more legible.
 
135
 
 
136
 
 
137
File: inform,  Node: Loops,  Next: Example 5,  Prev: Code Blocks,  Up: Routines
 
138
 
 
139
while, do...until, for, break, continue
 
140
---------------------------------------
 
141
 
 
142
   The other four Inform control constructs are all "loops", that is,
 
143
ways to repeat the execution of a given statement (or code block).
 
144
Discussion of one of the four, called objectloop, is deferred until
 
145
*Note Using the Tree::.
 
146
 
 
147
   The two basic forms of loop are while and do...until:
 
148
 
 
149
         while (<condition>) <statement>
 
150
         do <statement> until (<condition>)
 
151
 
 
152
The first repeatedly tests the condition and, provided it is still true,
 
153
executes the statement.  (If the condition is not even true the first
 
154
time, the statement is never executed.)  For example:
 
155
 
 
156
    [ SquareRoot n;
 
157
      x = n;
 
158
      while (x*x > n) x=x-1;
 
159
      return x;
 
160
    ];
 
161
 
 
162
a (fairly chronic) method for finding square roots.  (If SquareRoot(200)
 
163
is called, then x runs down through the values 200, 199, ..., 14, at
 
164
which point x*x <= n since 14 * 14 = 196.)
 
165
 
 
166
   The do...until loop repeats the given statement until the condition
 
167
is found to be true.  (Even if the condition is already satisfied, like
 
168
(true), the statement is always executed the first time through.)
 
169
 
 
170
   One particular kind of while loop is needed so often that there is an
 
171
abbreviation for it, called for.  For example,
 
172
 
 
173
    counter = 1;
 
174
    while (counter <= 10)
 
175
    {   print counter, " ";
 
176
        counter++;
 
177
    }
 
178
 
 
179
which produces the output
 
180
 
 
181
     1 2 3 4 5 6 7 8 9 10
 
182
 
 
183
(Recall that counter++ adds 1 to the variable counter.)  Languages like
 
184
BASIC make extensive use of this kind of loop.  For example, in BBC
 
185
BASIC, the above loop would be written
 
186
 
 
187
    FOR counter = 1 TO 10
 
188
        PRINT counter;" ";
 
189
    NEXT
 
190
 
 
191
NEXT is a word which (slightly clumsily) means "the code block ends
 
192
here", and is therefore the equivalent of Inform's }.  The whole is used
 
193
to mean "for values of the counter running through 1 to 10, do...",
 
194
hence the choice of the word FOR.
 
195
 
 
196
   Inform (like the language C) uses a more flexible construct than
 
197
this, but which is still called for.  It can produce any loop in the
 
198
form
 
199
 
 
200
         <start>
 
201
         while (<condition>)
 
202
         {   ...
 
203
             <update>
 
204
         }
 
205
 
 
206
where <start> and <update> are assignments.  The notation to achieve
 
207
this is
 
208
 
 
209
         for (<start> : <condition> : <update>) ...
 
210
 
 
211
For example, the loop described above is achieved by
 
212
 
 
213
    for (counter=1 : counter<=10 : counter++)
 
214
        print counter, " ";
 
215
 
 
216
Note that if the condition is false even the first time, the loop is
 
217
never executed.  For instance,
 
218
 
 
219
    for (counter=1 : counter<0 : counter++)
 
220
        print "Banana";
 
221
 
 
222
prints nothing.
 
223
 
 
224
!!  At this point it is worth mentioning that several assignments can
 
225
be combined into a single statement in Inform.  For example,
 
226
 
 
227
    i++, score=50, j++
 
228
 
 
229
(three assignments separated by commas) is a single statement.  This is
 
230
never useful in ordinary code, where the assignments can be divided up
 
231
by semicolons in the usual way.  In for loops it is useful, though:
 
232
 
 
233
    for (i=1, j=5: i<=5: i++, j--) print i, " ", j, ", ";
 
234
 
 
235
produces the output "1 5, 2 4, 3 3, 4 2, 5 1,".
 
236
 
 
237
   Any of the three parts of a for statement can be omitted.  If the
 
238
condition is missed out, it is assumed to be always true, i.e. there is
 
239
no check made to see if the loop should be ended and so the loop
 
240
continues forever.
 
241
 
 
242
   On the face of it, the following loops all repeat forever:
 
243
 
 
244
         while (true) <statement>
 
245
         do <statement> until (false)
 
246
         for (::) <statement>
 
247
 
 
248
But there is always an escape.  One way is to return from the current
 
249
routine.  Another is to jump to a label outside the loop (jump will be
 
250
covered in *Note Jumping Around:: below).  It's neater to use the
 
251
statement break, which causes execution to "break out of" the current
 
252
innermost loop or switch statement: it can be read as "finish early".
 
253
All these ways out are entirely "safe", and there is no harm in leaving
 
254
a loop only half-done.
 
255
 
 
256
   The other simple statement used inside loops is continue.  This
 
257
causes the current iteration to end immediately, but does not end the
 
258
whole loop.  For example,
 
259
 
 
260
    for (i=1: i<=5: i++)
 
261
    {   if (i==3) continue;
 
262
        print i, " ";
 
263
    }
 
264
 
 
265
will output "1 2 4 5".
 
266
 
 
267
 
 
268
File: inform,  Node: Example 5,  Next: Jumping Around,  Prev: Loops,  Up: Routines
 
269
 
 
270
Example 5: A number puzzle
 
271
--------------------------
 
272
 
 
273
   The routine RunPuzzle is an interesting example of a loop which,
 
274
though apparently simple enough, contains a trap for the unwary.
 
275
 
 
276
    [ RunPuzzle n count;
 
277
 
 
278
      do
 
279
      {   print n, " ";
 
280
          n = NextNumber(n);
 
281
          count++;
 
282
      }
 
283
      until (n==1);
 
284
      print "1^(taking ", count, " steps to reach 1)^";
 
285
    ];
 
286
    [ NextNumber n;
 
287
      if (n%2 == 0) return n/2;     ! If n is even, halve it
 
288
      return 3*n + 1;               ! If n is odd, triple and add 1
 
289
    ];
 
290
 
 
291
   The call RunPuzzle(10), for example, results in the output
 
292
 
 
293
         10 5 16 8 4 2 1
 
294
         (taking 6 steps to reach 1)
 
295
 
 
296
The source code assumes that, no matter what the initial value of n,
 
297
enough iteration will end up back at 1.  If this did not happen, the
 
298
program would lock up into an infinite loop, printing numbers forever.
 
299
 
 
300
   The routine is apparently very simple, so it would seem reasonable
 
301
that by thinking carefully enough about it, we ought to be able to
 
302
decide whether or not it is "safe" to use (i.e., whether it can be
 
303
guaranteed to finish or not).
 
304
 
 
305
   And yet nobody knows whether this routine is "safe".  The conjecture
 
306
that all n eventually step down to 1 is at least fifty years old but
 
307
has never been proved, having resisted all mathematical attack.
 
308
(Alarmingly, RunPuzzle(27) takes 111 iterations to fall back down to 1.)
 
309
 
 
310
 
 
311
File: inform,  Node: Jumping Around,  Next: Printing Output,  Prev: Example 5,  Up: Routines
 
312
 
 
313
quit, jump and the program state
 
314
--------------------------------
 
315
 
 
316
   There are four statements left which control the flow of execution.
 
317
quit ends the program immediately (as if a return had taken place from
 
318
the Main routine).  This drastic measure is best reserved for points in
 
319
the program which have detected some error condition so awful that
 
320
there is no point carrying on.  Better yet, do not use it at all.
 
321
 
 
322
   The jump statement transfers execution to some other named place in
 
323
the same routine.  (Some programming languages call this goto.  Since
 
324
it can be and has been put to ugly uses, the construct itself was at
 
325
one time frowned on as a vulgar construct leading programmers into sin.
 
326
Good use of control constructs will almost always avoid the need for
 
327
jump and result in more legible programs.  But sin is universal.)
 
328
 
 
329
   To use jump a notation is needed to mark particular places in the
 
330
source code.  Such markers are called "labels".  For example:
 
331
 
 
332
    [ Main i;
 
333
      i=1;
 
334
      .Marker;
 
335
      print "I have now printed this ", i++, " times.^";
 
336
      jump Marker;
 
337
    ];
 
338
 
 
339
This program has one label, Marker.  A statement consisting only of a
 
340
full stop and then an identifier means "put a label here and call it
 
341
this".
 
342
 
 
343
!!!! An Inform program has the ability to save a snapshot of its entire
 
344
state and to restore back to that previous state.  This snapshot
 
345
includes values of variables, the point where code is currently being
 
346
executed, and so on.  Just as we cannot know if the universe is only
 
347
six thousand years old, as creationists claim, having been endowed by
 
348
God with a carefully faked fossil record; so an Inform program cannot
 
349
know if it has been executing all along or if it was only recently
 
350
restarted.  The statements required are save and restore:
 
351
 
 
352
         save <label>
 
353
         restore <label>
 
354
 
 
355
This is a rare example of an Inform feature which may depend on the host
 
356
machine's state of health: for example, if all disc storage is full,
 
357
then save will fail.  It should always be assumed that these statements
 
358
may well fail.  A jump to the label provided occurs if the operation
 
359
has been a success.  (This is irrelevant in the case of a restore
 
360
since, if all has gone well, execution is now resuming from the
 
361
successful branch of the save statement: because that is where
 
362
execution was when the state was saved.)
 
363
 
 
364
 
 
365
File: inform,  Node: Printing Output,  Next: Example 6,  Prev: Jumping Around,  Up: Routines
 
366
 
 
367
Printing output
 
368
---------------
 
369
 
 
370
   When text is printed, normally each character is printed exactly as
 
371
specified in the source code.  Four characters, however, have special
 
372
meanings.  As explained above ^ means "print a new-line".  The
 
373
character ~, meaning "print a quotation mark", is needed since
 
374
quotation marks otherwise finish strings.  Thus,
 
375
 
 
376
    "~Look,~ says Peter. ~Socks can jump.~^Jane agrees."
 
377
 
 
378
is printed as
 
379
 
 
380
     "Look," says Peter. "Socks can jump."
 
381
     Jane agrees.
 
382
 
 
383
   The third remaining special character is @, which is used for
 
384
accented characters and other unusual effects, as described below.
 
385
Finally, \ is reserved for "folding lines", and used to be needed in
 
386
Inform 5 when text spilled over more than one line.  (It's no longer
 
387
needed but kept so that old programs still work.)  If you really want
 
388
to print a ~, a ^, an @ or a \, see below.
 
389
 
 
390
   Text still spills over more than one line, even in the present
 
391
golden age of Inform 6.  When a statement like
 
392
 
 
393
    print "Here in her hairs
 
394
           the painter plays the spider, and hath woven
 
395
           a golden mesh t'untrap the hearts of men
 
396
           faster than gnats in cobwebs";
 
397
 
 
398
is read in by Inform, the line breaks are replaced with a single space
 
399
each.  Thus the text printed is: "Here in her hairs the painter plays
 
400
the spider, and hath woven a golden mesh..." and so on.  (There is one
 
401
exception: if a line finishes with a ^ (new-line) character, then no
 
402
space is added before the next line begins.)
 
403
 
 
404
   So far, only the print statement has been used for printing, to
 
405
print both numbers and strings (that is, double-quoted pieces of text).
 
406
Since Inform is primarily a language for writing Adventure games, its
 
407
business is text, and it provides many other facilities for printing.
 
408
 
 
409
         new_line
 
410
 
 
411
is a statement which simply prints a new-line (otherwise known as a
 
412
carriage return, as if the lever on the carriage of an old manual
 
413
typewriter had been pulled to move it right back to the left margin and
 
414
turn it forward one line).  This is equivalent to
 
415
 
 
416
         print "^"
 
417
 
 
418
but is a convenient abbreviation.  Similarly,
 
419
 
 
420
         spaces <number>
 
421
 
 
422
prints a sequence of that many spaces.
 
423
 
 
424
         inversion
 
425
 
 
426
prints the version number of Inform which was used to compile the
 
427
program (it might, for instance, print "6.01").
 
428
 
 
429
         box <string1> ... <stringn>
 
430
 
 
431
displays a reverse-video box in the centre of the screen, containing
 
432
 
 
433
         string1
 
434
         string2
 
435
           ...
 
436
         stringn
 
437
 
 
438
and is usually used for popping up quotations: for example,
 
439
 
 
440
    box "Passio domini nostri" "Jesu Christi Secundum" "Joannem"
 
441
 
 
442
displays
 
443
 
 
444
         Passio domini nostri
 
445
         Jesu Christi Secundum
 
446
         Joannem
 
447
 
 
448
(the opening line of the libretto to Arvo Part's `St John Passion').
 
449
 
 
450
Text is normally displayed in ordinary (or "Roman") type.  Its actual
 
451
appearance will vary from machine to machine running the program.  On
 
452
many machines, it will be displayed using a "font" which is
 
453
variably-pitched, so that for example a "w" will be wider on-screen
 
454
than an "i".  Such text is much easier to read, but makes it very
 
455
difficult to print out diagrams.  The statement
 
456
 
 
457
    print "+------------+
 
458
          ^+   Hello    +
 
459
          ^+------------+^";
 
460
 
 
461
will print something quite irregular if the characters "-", "+" and " "
 
462
(space) do not all have the same width.  Because one sometimes does
 
463
want to print such a diagram (to represent a sketch-map, say, or to
 
464
print out a table), the statement font is provided:
 
465
 
 
466
    font on
 
467
    font off
 
468
 
 
469
font off switches into a fixed-pitch display style (in which all
 
470
characters definitely have the same width); font on goes back to the
 
471
original.
 
472
 
 
473
   In addition to this, a few textual effects can be achieved.
 
474
 
 
475
    style roman
 
476
 
 
477
switches to ordinary Roman text (the default), and there are also
 
478
 
 
479
    style bold
 
480
    style underline
 
481
    style reverse
 
482
 
 
483
(reverse meaning "reverse colour": e.g. yellow on blue if the normal
 
484
text appearance is blue on yellow).  An attempt will be made to
 
485
approximate these effects on any machine, but it may be that underline
 
486
comes out as italicised text, for example, or that bold is rendered by
 
487
printing ordinary Roman text but in a different colour.
 
488
 
 
489
Inform programs are starting to be written which communicate in
 
490
languages other than English: Italian, Dutch, German, French and
 
491
Spanish games have all been attempted.  A comprehensive range of
 
492
accented characters is available: these are reached with the aid of the
 
493
escape character, @.
 
494
 
 
495
Most accented characters are written as @, followed by an accent marker,
 
496
then the letter on which the accent appears:
 
497
     @^ put a circumflex on the next letter: a,e,i,o,u,A,E,I,O or U
 
498
     @' put an acute on the next letter: a,e,i,o,u,y,A,E,I,O,U or Y
 
499
     @` put a grave on the next letter: a,e,i,o,u,A,E,I,O or U
 
500
     @: put a diaeresis on the next letter: a,e,i,o,u,A,E,I,O or U
 
501
     @c put a cedilla on the next letter: c or C
 
502
     @~ put a tilde on the next letter: a,n,o,A,N or O
 
503
     @" put a slash on the next letter: o or O
 
504
     @o put a ring on the next letter: a or A
 
505
 
 
506
In addition, there are a few others:
 
507
     @ss German sz
 
508
     @<< continental European quotation marks
 
509
     @>>
 
510
     @ae ligatures
 
511
     @AE
 
512
     @oe
 
513
     @OE
 
514
     @th       Icelandic accents
 
515
     @et
 
516
     @Th
 
517
     @Et
 
518
     @LL pound sign
 
519
     @!! Spanish (upside-down) exclamation mark
 
520
     @?? Spanish (upside-down) question mark
 
521
 
 
522
For instance,
 
523
 
 
524
    print "Les @oeuvres d'@Aesop en fran@ccais, mon @'el@`eve!";
 
525
    print "Na@:ive readers of the New Yorker will re@:elect Mr Clinton.";
 
526
    print "Carl Gau@ss first proved the Fundamental Theorem of Algebra.";
 
527
 
 
528
Accented characters can also be referred to as constants, like other
 
529
characters.  Just as 'x' represents the character lower-case-X, so
 
530
'@^A' represents capital-A-circumflex.
 
531
 
 
532
!!  The @ escape character has two other uses.  One gets around the
 
533
problem that, so far, it is impossible to print an "@".  A double @
 
534
sign, followed by a number, prints the character with this numerical
 
535
code.  The most useful cases are:
 
536
           @@92      comes out as "\"
 
537
           @@64      comes out as "@"
 
538
           @@94      comes out as "^"
 
539
           @@126     comes out as "~"
 
540
 
 
541
enabling us to print the four characters which can't be typed directly
 
542
because they have other meanings.
 
543
 
 
544
!!!! The second use is more obscure.  Inform keeps a stock of 32
 
545
pseudo-variables to hold text, numbered from 0 to 31.
 
546
           @00       prints out as the current contents of string 0
 
547
           ...       ...
 
548
           @31       prints out as the current contents of string 31
 
549
 
 
550
and these variables are set with the string statement:
 
551
 
 
552
    string 0 "toadstool";
 
553
 
 
554
sets string 0 to the text of the word "toadstool".  (There is a
 
555
technical reason why these strings cannot be set equal to any text:
 
556
only to literal text, as in the above example, or to strings previously
 
557
declared using the Low_string directive.)
 
558
 
 
559
   Finally, it is time to discuss print.  There are two forms, print
 
560
and print_ret.  The only difference is that the second prints out an
 
561
extra new-line character and returns from the current routine with the
 
562
value true.  Thus, print_ret should be read as "print and then return",
 
563
and
 
564
 
 
565
    print_ret "That's enough of that.";
 
566
 
 
567
is equivalent to
 
568
 
 
569
    print "That's enough of that.^"; rtrue;
 
570
 
 
571
In fact, as an abbreviation, it can even be shortened to:
 
572
 
 
573
    "That's enough of that.";
 
574
 
 
575
Although Inform newcomers are often confused by the fact that this
 
576
apparently innocent statement actually causes a return from the current
 
577
routine, it's an abbreviation which very much pays off in
 
578
adventure-writing situations.  Note that if the program:
 
579
 
 
580
    [ Main;
 
581
      "Hello, and now for a number...";
 
582
      print 45*764;
 
583
    ];
 
584
 
 
585
is compiled, Inform will produce the warning message:
 
586
 
 
587
    line 3: Warning: This statement can never be reached.
 
588
    >   print 45*764;
 
589
 
 
590
because the bare string on line 2 is printed using print_ret: so the
 
591
text is printed, then a new-line is printed, and then a return takes
 
592
place immediately.  As the warning message indicates, there is no way
 
593
the statement on line 3 can ever be executed.
 
594
 
 
595
   So what can be printed?  The answer is a list of terms, separated by
 
596
commas.  For example,
 
597
 
 
598
    print "The value is ", value, ".";
 
599
 
 
600
contains three terms.  A term can take the following forms:
 
601
      <a numerical quantity>       printed as a (signed, decimal) number
 
602
      <text in double-quotes>      printed as text
 
603
      (<rule>) <quantity>          printed according to some special rule
 
604
 
 
605
   Inform provides a stock of special printing rules built-in, and also
 
606
allows the programmer to create new ones.  The most important rules are:
 
607
    (char)    print out the character which this is the numerical code for
 
608
    (string)  print this string out
 
609
    (address) print out the text at this array address
 
610
              (this is seldom used, and then mainly to print the
 
611
               text of a word entry in a game's dictionary)
 
612
 
 
613
!! print (string) ... requires a little explanation.
 
614
 
 
615
    x = "Hello!";
 
616
    print (string) x;
 
617
 
 
618
prints out "Hello!", whereas
 
619
 
 
620
    x = "Hello!";
 
621
    print x;
 
622
 
 
623
prints a mysterious number.  This is because strings are internally
 
624
represented by numbers (just as everything else is).
 
625
 
 
626
   The remaining stock of rules is provided for use in conjunction with
 
627
the Library and is documented in Chapter V: briefly,
 
628
         (the)      print definite article then name of this object
 
629
         (The)      ditto, but capitalised
 
630
         (name)     ditto, but with no article
 
631
         (a)        ditto, but with the indefinite article
 
632
         (number)   print this number out in English
 
633
         (property) (for debugging) print the name of this property
 
634
         (object)   (ditto) print the hardware-name of this object
 
635
 
 
636
Note that (the) in lower case does something different from (The) with
 
637
an upper case T.  This is very unusual!  (Directive names, which will
 
638
turn up in *Note Data Structures::, variable names and so on are
 
639
allowed to use upper case and the case is simply ignored, so that fRoG
 
640
means the same as frog.  But statement keywords, like print or (name),
 
641
have to be in lower case -- except for (The).)
 
642
 
 
643
   To create a new rule, provide a routine with this name, and use the
 
644
rule-name in brackets.
 
645
 
 
646
 
 
647
File: inform,  Node: Example 6,  Next: Random and Indirect,  Prev: Printing Output,  Up: Routines
 
648
 
 
649
Example 6: Printing in hexadecimal
 
650
----------------------------------
 
651
 
 
652
   The following pair of routines provides for printing out a number as
 
653
a four-digit, unsigned hexadecimal number.  For example, so that
 
654
 
 
655
    print (hex) 16339;
 
656
 
 
657
prints "3fd3".
 
658
 
 
659
    [ hex x y;
 
660
      y = (x & $ff00) / $100;
 
661
      x = x & $ff;
 
662
      print (hdigit) y/$10, (hdigit) y, (hdigit) x/$10, (hdigit) x;
 
663
    ];
 
664
    [ hdigit x;
 
665
      x = x % $10;
 
666
      if (x<10) print x; else print (char) 'a'+x-10;
 
667
    ];
 
668
 
 
669
Once these routines have been defined, hex and hdigit are available
 
670
anywhere in the same program for use as new printing rules.
 
671
 
 
672
 
 
673
File: inform,  Node: Random and Indirect,  Next: Accepting Input,  Prev: Example 6,  Up: Routines
 
674
 
 
675
Built-in functions 1: random and indirect
 
676
-----------------------------------------
 
677
 
 
678
   Inform provides a small stock of functions ready-defined, but which
 
679
are used much as other functions are.  All but two of these concern
 
680
objects and will be left until chapter 3.
 
681
 
 
682
random has two forms:
 
683
 
 
684
         random(N)
 
685
 
 
686
returns a uniformly random number in the range 1, 2, ..., N.  N should
 
687
always be a positive number (between 1 and 32767) for this to work
 
688
properly.
 
689
 
 
690
         random(two or more constant quantities, separated by commas)
 
691
 
 
692
returns a uniformly random choice from this selection.  Thus,
 
693
 
 
694
    print (string) random("red", "blue", "green", "purple", "orange");
 
695
 
 
696
randomly prints the name of one of these five colours (each being
 
697
equally likely to appear).  Likewise,
 
698
 
 
699
    print random(13, 17);
 
700
 
 
701
has a 50% chance of printing 13, and a 50% chance of printing 17.
 
702
 
 
703
!!!! The other built-in function discussed here is indirect.
 
704
 
 
705
    indirect(function, arg1, arg2, ...)
 
706
 
 
707
calls the given function with given arguments.  Thus, this is
 
708
equivalent to
 
709
 
 
710
    function(arg1, arg2, ...)
 
711
 
 
712
but has the additional virtue that the function can be given, not just
 
713
as a literal function name, but as some calculated value:
 
714
 
 
715
    indirect(random(OneRoutine, OtherRoutine), 45);
 
716
 
 
717
has a 50% chance of calling OneRoutine(45), and a 50% chance of calling
 
718
OtherRoutine(45).  indirect should be used with caution: if supplied
 
719
with a numerical first argument which doesn't correspond to any
 
720
function in the program, the program may resoundingly crash.  In any
 
721
event, it is often best to achieve such effects using messages to
 
722
objects.
 
723
 
 
724
 
 
725
File: inform,  Node: Accepting Input,  Prev: Random and Indirect,  Up: Routines
 
726
 
 
727
Accepting input
 
728
---------------
 
729
 
 
730
!!!!  Inform programmers seldom need to take input from the keyboard,
 
731
in practice, since in all game situations the Library's parser routines
 
732
take care of all that.  However, for completeness this section covers
 
733
the read statement which is the main route by which keyboard input is
 
734
taken.  It will not make much sense to readers who have not yet read
 
735
the rest of this book.
 
736
 
 
737
   The syntax is
 
738
 
 
739
         read <text array> <parse buffer> <routine>
 
740
 
 
741
where the <routine> is optional: if provided, it is called just before
 
742
the input takes place so that the screen's top line or lines of data
 
743
(the "status line" present in many games) can be renewed.
 
744
 
 
745
   What the statement does is to read in a single line of text (waiting
 
746
until the user has finished typing a line and then pressed RETURN),
 
747
copy this text into the text array and then try to comprehend it,
 
748
writing the results of this comprehension exercise ("parsing") into the
 
749
parse buffer.
 
750
 
 
751
   Before the statement is reached, the program should have entered the
 
752
maximum number of characters which can be accepted (say, 60) into the
 
753
0th entry of the text array; the statement will then write the actual
 
754
number typed into the 1st entry, and the characters themselves into
 
755
entries 2 and onward.  Thus,
 
756
 
 
757
    text_array -> 0 = 60;
 
758
    read text_array 0;
 
759
    for (n = 0: n< text_array->1: n++) print (char) text_array->(n+2);
 
760
    new_line;
 
761
 
 
762
will read in a line of up to 60 characters, and then print it back
 
763
again.  (The array text_array must have been created first, and so must
 
764
the local variable n, of course.)
 
765
 
 
766
   Note that in this case, no "parse buffer" has been given (0 was
 
767
given in its place).  If, instead of 0, an array is given here, then
 
768
the read statement makes an attempt to divide up the input text into
 
769
individual words, and to match these words against the game's
 
770
dictionary.  See *Note Special Data Structures:: for details.
 
771
 
 
772
 
 
773
File: inform,  Node: Data Structures,  Next: Objects,  Prev: Routines,  Up: Programming Language
 
774
 
 
775
The language of data structures
 
776
===============================
 
777
 
 
778
* Menu:
 
779
 
 
780
* Directives and Constants::    Directives and global constants
 
781
* Global Variables::            Variables usable by the entire program
 
782
* Arrays::                      Arrays hold a sequence of values
 
783
* Example 7::                   An array example: shuffling a pack of cards
 
784
* Special Data Structures::     Seven special data structures in all programs
 
785
 
 
786
 
 
787
File: inform,  Node: Directives and Constants,  Next: Global Variables,  Prev: Data Structures,  Up: Data Structures
 
788
 
 
789
Directives and constants
 
790
------------------------
 
791
 
 
792
   Every example program so far has consisted only of a sequence of
 
793
routines, each within beginning and end markers [ and ].  Such routines
 
794
have no way of communicating with each other, and therefore of sharing
 
795
information with each other, except by making function calls back and
 
796
forth.  This arrangement is not really suited to a large program whose
 
797
task may be to simulate something complicated (such as the world of an
 
798
adventure game): it would be useful to have some kind of central
 
799
registry of information which all routines have access to, as and when
 
800
needed.
 
801
 
 
802
   Information available to all routines in this way is said to be
 
803
"global", rather than "local" to any one routine.  (As will appear in
 
804
*Note Objects::, there is also an intermediate possibility where
 
805
information is available only to a cluster of routines working on
 
806
roughly the same part of a program.)
 
807
 
 
808
   This global information can be organised in a variety of ways.  Such
 
809
organised groups are called "data structures".  For example, a typical
 
810
data structure might be a list of 10 values.  The term "data structure"
 
811
did not appear in *Note Routines:: because information was only ever
 
812
held in variables, the simplest possible kind of structure (one value
 
813
on its own).
 
814
 
 
815
   Data structures are added to Inform programs using commands called
 
816
"directives" in between definitions of routines.  It's important to
 
817
distinguish between these, which direct Inform to do something now
 
818
(usually, to create something) and the statements which occur inside
 
819
routines, which are merely translated in some way but not acted on
 
820
until the program has finished being compiled and is run.
 
821
 
 
822
   In fact, one directive has already appeared: the one written [,
 
823
which means "translate the following routine up to the next ]".  In all
 
824
there are 38 Inform directives, as follows:
 
825
 
 
826
Abbreviate  Array       Attribute  Class        Constant     Default
 
827
Dictionary  End         Endif      Extend       Fake_action  Global
 
828
Ifdef       Ifndef      Ifnot      Ifv3         Ifv5         Iftrue
 
829
Iffalse     Import      Include    Link         Lowstring    Message
 
830
Nearby      Object      Property   Release      Replace      Serial
 
831
Switches    Statusline  Stub       System_file  Trace        Verb
 
832
Version     [
 
833
 
 
834
Several of these are rather technical and will not be used by many
 
835
programmers (such as Trace, Stub, Default, System_file, Abbreviate,
 
836
Dictionary).  Others control fine points of what is compiled and what
 
837
isn't (Ifdef, Ifnot, and so on; Message, Replace).  These not-very
 
838
important directives are covered in Chapter II.
 
839
 
 
840
   This leaves 9 central directives for creating data structures, and
 
841
these are the ones which it is important to know about:
 
842
 
 
843
Array       Attribute   Class      Constant     Extend       Global
 
844
Object      Property    Verb
 
845
 
 
846
It is conventional to write these with the initial letter capitalised:
 
847
this makes directives look unlike statements.  Attribute, Class, Object
 
848
and Property are the subject of *Note Objects::.
 
849
 
 
850
The simplest directive with a "global" effect on the program -- an
 
851
effect all over the program, that is, not just in one routine -- is
 
852
Constant.  The following program, an unsatisfying game of chance, shows
 
853
a typical use of Constant.
 
854
 
 
855
    Constant MAXIMUM_SCORE = 100;
 
856
 
 
857
    [ Main;
 
858
      print "You have scored ", random(MAXIMUM_SCORE),
 
859
      " points out of ", MAXIMUM_SCORE, ".^";
 
860
    ];
 
861
 
 
862
   The maximum score value is used twice in the routine Main.  Of
 
863
course the program is the same as it would have been if the constant
 
864
definition were not present, and MAXIMUM_SCORE were replaced by 100 in
 
865
both places where it occurs.  The advantage of using Constant is that
 
866
it makes it possible to change this value from 100 to, say, 50 with
 
867
only a single change, and it makes the source code more legible to the
 
868
reader by explaining what the significance of the number 100 is
 
869
supposed to be.
 
870
 
 
871
   If no value is specified for a constant, as in the line
 
872
 
 
873
    Constant DEBUG;
 
874
 
 
875
then the constant is created with value 0.
 
876
 
 
877
 
 
878
File: inform,  Node: Global Variables,  Next: Arrays,  Prev: Directives and Constants,  Up: Data Structures
 
879
 
 
880
Global variables
 
881
----------------
 
882
 
 
883
   As commented above, so far the only variables allowed have been
 
884
"local variables", each private to their own routines.  A "global
 
885
variable" is a variable which is accessible to all code in every
 
886
routine.  Once a global variable has been declared, it is used in just
 
887
the same way as a local variable.  The directive for declaring a global
 
888
variable is Global:
 
889
 
 
890
    Global score = 36;
 
891
 
 
892
This creates a variable called score, which at the start of the program
 
893
has the value 36.  score can be altered or used anywhere in the program
 
894
after the line on which it is defined.
 
895
 
 
896
 
 
897
File: inform,  Node: Arrays,  Next: Example 7,  Prev: Global Variables,  Up: Data Structures
 
898
 
 
899
Arrays
 
900
------
 
901
 
 
902
   An "array" is an indexed collection of (global) variables, holding a
 
903
set of numbers organised into a sequence. It allows general rules to be
 
904
given for how a group of variables should be treated.  For instance,
 
905
the directive
 
906
 
 
907
    Array pack_of_cards --> 52;
 
908
 
 
909
creates a stock of 52 variables, referred to in the program as
 
910
 
 
911
    pack_of_cards-->0   pack_of_cards-->1   ...   pack_of_cards-->51
 
912
 
 
913
There are two basic kinds of array: "word arrays" (written using --> as
 
914
above) and "byte arrays" (written using -> similarly).  Whereas the
 
915
entries of a word array can hold any number, the entries of a byte
 
916
array can only be numbers in the range 0 to 255 inclusive.  (The only
 
917
advantage of this is that it is more economical on memory, and
 
918
beginners are advised to use word arrays instead.)
 
919
 
 
920
   In addition to this, Inform provides arrays which have a little extra
 
921
structure: they are created with the 0th entry holding the number of
 
922
entries.  A word array with this property is called a table; a byte
 
923
array with this property is a string.
 
924
 
 
925
   For example, the array defined by
 
926
 
 
927
    Array continents table 5;
 
928
 
 
929
has six entries: continents-->0, which holds the number 5, and five more
 
930
entries, indexed 1 to 5.  (The program is free to change continents-->0
 
931
later but this will not change the size: the size of an array can never
 
932
change.) As an example of using string arrays:
 
933
 
 
934
    Array password string "DANGER";
 
935
    Array phone_number string "1978-345-2160";
 
936
    ...
 
937
    PrintString(password);
 
938
    ...
 
939
    PrintString(phone_number);
 
940
    ...
 
941
    [ PrintString the_array i;
 
942
        for (i=1: i<=the_array->0: i++)
 
943
            print (char) the_array->i;
 
944
    ];
 
945
 
 
946
The advantage of string arrays, then, is that one can write a general
 
947
routine like PrintString which works for arrays of any size.
 
948
 
 
949
   To recapitulate, Inform provides four kinds of array in all:
 
950
 
 
951
    -->   ->   table   string
 
952
 
 
953
There are also four different ways to set up an array with its initial
 
954
contents (so the directive can take 16 forms in all).  In all of the
 
955
examples above, the array entries will all contain 0 when the program
 
956
begins.
 
957
 
 
958
   Instead, we can give a list of constant values.  For example,
 
959
 
 
960
    Array primes --> 2 3 5 7 11 13;
 
961
 
 
962
is a word array created with six entries, primes-->0 to primes-->5,
 
963
initially holding the values 2 to 13.
 
964
 
 
965
   The third way to create an array gives some text as an initial value
 
966
(because one common use for arrays is as "strings of characters" or
 
967
"text buffers").  The two string arrays above were set up this way.  As
 
968
another example,
 
969
 
 
970
    Array players_name -> "Frank Booth";
 
971
 
 
972
sets up the byte array players_name as if the directive had been
 
973
 
 
974
    Array players_name -> 'F' 'r' 'a' 'n' 'k' ' ' 'B' 'o' 'o' 't' 'h';
 
975
 
 
976
!!!! The fourth way to create an array is obsolete and is kept only so
 
977
that old programs still work.  This is to give a list of values in
 
978
between end-markers [ and ], separated by commas or semi-colons.  Please
 
979
don't use this any longer.
 
980
 
 
981
   *Warning:* It is up to the programmer to see that no attempt is made
 
982
to read or write non-existent entries of an array.  (For instance,
 
983
pack_of_cards-->1000.)  Such mistakes are notorious for causing programs
 
984
to fail in unpredictable ways, difficult to diagnose.  Here for example
 
985
is an erroneous program:
 
986
 
 
987
    Array ten --> 10;
 
988
    Array fives --> 5 10 15 20 25;
 
989
    [ Main n;
 
990
      for (n=1: n<=10: n++) ten-->n = -1;
 
991
      print fives-->0, "^";
 
992
    ];
 
993
 
 
994
This program ought to print 5 (since that's the 0-th entry in the array
 
995
fives), but in fact it prints -1.  The problem is that the entries of
 
996
ten are ten-->0 up to ten-->9, not (as the program implicitly assumes)
 
997
ten-->1 to ten-->10.  So the value -1 was written to ten-->10, an entry
 
998
which does not exist.  At this point anything could have happened.  As
 
999
it turned out, the value was written into the initial entry of the next
 
1000
array along, "corrupting" the data there.
 
1001
 
 
1002
 
 
1003
File: inform,  Node: Example 7,  Next: Special Data Structures,  Prev: Arrays,  Up: Data Structures
 
1004
 
 
1005
Example 7: Shuffling a pack of cards
 
1006
------------------------------------
 
1007
 
 
1008
   This program simulates the shuffling of a pack of playing cards.
 
1009
The cards are represented by numbers in the range 0 (the Ace of Hearts)
 
1010
to 51 (the King of Spades).  The pack itself has 52 positions, from
 
1011
position 0 (on the top) to position 51 (on the bottom).  It is
 
1012
therefore represented by the array
 
1013
 
 
1014
    pack_of_cards-->i
 
1015
 
 
1016
whose i-th entry is the card number at position i.  A new pack as
 
1017
produced by the factory, still in order, would therefore be represented
 
1018
with card i in position i: the pack would have the Ace of Hearts on top
 
1019
and the King of Spades on the bottom.
 
1020
 
 
1021
    Constant SHUFFLES = 100;
 
1022
    Array pack_of_cards --> 52;
 
1023
 
 
1024
    [ ExchangeTwo x y z;
 
1025
 
 
1026
      !   Initially x and y are both zero
 
1027
 
 
1028
      while (x==y)
 
1029
      {   x = random(52) - 1; y = random(52) - 1;
 
1030
      }
 
1031
 
 
1032
      !   x and y are now randomly selected, different numbers
 
1033
      !   in the range 0 to 51
 
1034
 
 
1035
      z = pack_of_cards-->x;
 
1036
      pack_of_cards-->x = pack_of_cards-->y;
 
1037
      pack_of_cards-->y = z;
 
1038
    ];
 
1039
 
 
1040
    [ Card n;
 
1041
      switch(n%13)
 
1042
      {   0: print "Ace";
 
1043
          1 to 9: print n%13 + 1;
 
1044
          10: print "Jack";
 
1045
          11: print "Queen";
 
1046
          12: print "King";
 
1047
      }
 
1048
      print " of ";
 
1049
      switch(n/13)
 
1050
      {   0: print "Hearts";
 
1051
          1: print "Clubs";
 
1052
          2: print "Diamonds";
 
1053
          3: print "Spades";
 
1054
      }
 
1055
    ];
 
1056
 
 
1057
    [ Main i;
 
1058
      !   Create the pack in "factory order":
 
1059
      for (i=0:i<52:i++) pack_of_cards-->i = i;
 
1060
      !   Exchange random pairs of cards for a while:
 
1061
      for (i=0:i<SHUFFLES:i++) ExchangeTwo();
 
1062
      print "The pack has been shuffled to contain:^";
 
1063
      for (i=0:i<52:i++)
 
1064
          print (Card) pack_of_cards-->i, "^";
 
1065
    ];
 
1066
 
 
1067
   Note the use of a "printing rule" called Card to describe card
 
1068
number i.  Note also that 100 exchanges of pairs of cards is only just
 
1069
enough to make the pack appear well shuffled.  Redefining SHUFFLES as
 
1070
10000 makes the program take longer; redefining it as 10 makes the
 
1071
result very suspect.
 
1072
 
 
1073
!! The example code shuffles the pack in a simple way, but there are
 
1074
more efficient methods.  Here's one supplied by Dylan Thurston, giving
 
1075
perfect randomness in 51 exchanges.
 
1076
 
 
1077
        pack_of_cards-->0 = 0;
 
1078
        for (i=1:i<52:i++)
 
1079
        {   j = random(i+1) - 1;
 
1080
            pack_of_cards-->i = pack_of_cards-->j; pack_of_cards-->j = i;
 
1081
        }
 
1082
 
 
1083
 
 
1084
File: inform,  Node: Special Data Structures,  Prev: Example 7,  Up: Data Structures
 
1085
 
 
1086
Seven special data structures
 
1087
-----------------------------
 
1088
 
 
1089
!! All Inform programs automatically contain seven special data
 
1090
structures, each being one of a kind: the object tree, the grammar, the
 
1091
table of actions, the release number, the serial code, the "statusline
 
1092
flag" and the dictionary.  These data structures are tailor-made for
 
1093
adventure games and (except for the object tree) can be ignored for
 
1094
every other kind of program.  So they are mostly covered in Book Two.
 
1095
 
 
1096
  1. For the object tree (and the directives Object and Class), see
 
1097
     *Note Objects::.
 
1098
 
 
1099
  2. For grammar (and the directives Verb and Extend), see Chapter V,
 
1100
     *Note Parsing Verbs:: and *Note Grammar Tokens::.
 
1101
 
 
1102
  3. For actions (and the <...> and <<...>> statements and the ##
 
1103
     constant notation), see Chapter III, *Note Actions and Reactions::.
 
1104
 
 
1105
  4. The release number (which is printed automatically by the library
 
1106
     in an Inform-written adventure game) is 1 unless otherwise
 
1107
     specified.  The directive
 
1108
 
 
1109
         Release <number>;
 
1110
 
 
1111
     does this.  Conventionally release 1 would be the first published
 
1112
     copy, and releases 2, 3, ... would be amended re-releases.  See
 
1113
     Chapter III, *Note Getting Started::, for an example.
 
1114
 
 
1115
  5. The serial number is set automatically to the date of compilation
 
1116
     in the form 960822 ("22nd August 1996").  This can be overridden
 
1117
     if desired with the directive
 
1118
 
 
1119
         Serial "dddddd";
 
1120
 
 
1121
     where the text must be a string of 6 digits.
 
1122
 
 
1123
  6. The "status line flag" chooses between styles of "status line" at
 
1124
     the top of an adventure game's screen display.  See Chapter IV,
 
1125
     *Note Daemons::, for use of the Statusline directive.
 
1126
 
 
1127
  7. The dictionary is automatically built by Inform.  It is a stock of
 
1128
     all the English words which the game might want to recognise from
 
1129
     what the player has typed: it includes any words written in
 
1130
     constants like 'duckling', as well as any words given in name
 
1131
     values or in grammar.  For example
 
1132
 
 
1133
         if (first_word == 'herring') print "You typed the word herring!";
 
1134
 
 
1135
     is a legal statement.  Inform notices that herring -- because it
 
1136
     is in single quotes -- is a word the program may one day need to
 
1137
     be able to recognise, so it adds the word to the dictionary.  Note
 
1138
     that the constant 'herring' is a dictionary word but the constant
 
1139
     'h' is the ASCII value of lower-case H.  (Single-letter dictionary
 
1140
     words are seldom needed, but can be written using an ugly syntax
 
1141
     if need be: #n$h is the constant meaning "the dictionary word
 
1142
     consisting only of the letter H".)
 
1143
 
 
1144
!!!!  From this description, the dictionary appears to be something
 
1145
into which words are poured, never to re-emerge.  The benefit is felt
 
1146
when the read statement comes to try to parse some input text:
 
1147
 
 
1148
    read text_array parse_buffer;
 
1149
 
 
1150
It must be emphasized that the read statement performs only the simplest
 
1151
possible form of parsing, and should not be confused with the very much
 
1152
more elaborate parser included in the Inform library.
 
1153
 
 
1154
   What it does is to break down the line of input text into a sequence
 
1155
of words, in which commas and full stops count as separate words in
 
1156
their own right.  (An example is given in Chapter V, *Note Parsing
 
1157
Nouns::.) Before using read, the entry
 
1158
 
 
1159
    parse_buffer->0
 
1160
 
 
1161
should be set to the maximum number of words which parsing is wanted
 
1162
for.  (Any further words will be ignored.)  The number of words
 
1163
actually parsed from the text is written in
 
1164
 
 
1165
    parse_buffer->1
 
1166
 
 
1167
and a block of data is written into the array for each of these words:
 
1168
 
 
1169
    parse_buffer-->(n*2 - 1)
 
1170
 
 
1171
holds the dictionary value of the n-th word (if n counts 1, 2, 3, ...).
 
1172
If the word isn't in the dictionary, this value is zero.
 
1173
 
 
1174
(In addition,
 
1175
 
 
1176
    parse_buffer->(n*4)
 
1177
    parse_buffer->(n*4 + 1)
 
1178
 
 
1179
are set to the number of letters in word n, and the offset of word n in
 
1180
the text array.)
 
1181
 
 
1182
For example,
 
1183
 
 
1184
    [ PleaseTypeYesOrNo i;
 
1185
      for (::)
 
1186
      {   buffer->0 = 60;
 
1187
          parse->0 = 1;
 
1188
          print "Please type ~yes~ or ~no~> ";
 
1189
          read buffer parse;
 
1190
          if (parse-->1 == 'yes') rtrue;
 
1191
          if (parse-->1 == 'no')  rfalse;
 
1192
      }
 
1193
    ];
 
1194
 
 
1195
 
 
1196
File: inform,  Node: Objects,  Prev: Data Structures,  Up: Programming Language
 
1197
 
 
1198
The language of objects
 
1199
=======================
 
1200
 
 
1201
     Objects make up the substance of the world.  That is why they
 
1202
     cannot be composite.
 
1203
 
 
1204
     -- Ludwig Wittgenstein (1889-1951), Tractatus
 
1205
 
 
1206
* Menu:
 
1207
 
 
1208
* About Objects::               Objects and communication
 
1209
* Object Tree::                 The object tree and functions for reading it
 
1210
* Creating Objects::            Creating objects and setting up the object tree
 
1211
* Using the Tree::              `move', `remove', `in', and `objectloop'
 
1212
* Objects with Properties::     Creating objects with properties
 
1213
* Private Properties::          Using `private' properties for encapsulation
 
1214
* Using Attributes::            Using `give' and `has' to manipulate attributes
 
1215
* Classes and Inheritance::     Creating classes of related objects
 
1216
* Messages::                    You communicate with objects via messages
 
1217
* Access to Superclass Values:: Using an overridden value from a parent class
 
1218
* Philosophy::                  The theory behind this object-oriented design
 
1219
* Sending Messages::            Send messages to routines, strings, and classes
 
1220
* Dynamic Objects::             Creating and deleting objects at run time
 
1221
* Common vs Individual::        Object properties can be common or individual
 
1222
 
 
1223
 
 
1224
File: inform,  Node: About Objects,  Next: Object Tree,  Prev: Objects,  Up: Objects
 
1225
 
 
1226
Objects and communication
 
1227
-------------------------
 
1228
 
 
1229
   The objects in a program are its constituent parts: little lumps of
 
1230
code and data.  The starting point of an "object-oriented language" is
 
1231
that it's good design to tie up pieces of information in bundles with
 
1232
the pieces of program which deal with them.  But the idea goes further:
 
1233
 
 
1234
  1. An object is something you can communicate with.  (It's like a
 
1235
     company where many people work in the same building, sharing the
 
1236
     same address: to the outside world it behaves like a single
 
1237
     person.)
 
1238
 
 
1239
  2. Information inside the object can be kept concealed from the
 
1240
     outside world (like a company's confidential files).  This is
 
1241
     sometimes called "encapsulation".
 
1242
 
 
1243
  3. The outside world can only ask the object to do something, and has
 
1244
     no business knowing how it will be done.  (The company might
 
1245
     decide to change its stock-control system one day, but the outside
 
1246
     world should never even notice that this has happened, even though
 
1247
     internally it's a dramatic shift.)
 
1248
 
 
1249
All three principles have been seen already for routines: (1) you can
 
1250
call a routine, but you can't call "only this part of a routine"; (2)
 
1251
the local variables of a routine are its own private property, and the
 
1252
rest of the program can't find out or alter their values; (3) as long
 
1253
as the routine still accomplishes the same task, it can be rewritten
 
1254
entirely and the rest of the program will carry on working as if no
 
1255
change had been made.
 
1256
 
 
1257
   Why bother with all this?  There are two answers.  First and
 
1258
foremost, Inform was designed to make adventure games, where objects
 
1259
are the right idea for representing items and places in the game.
 
1260
Secondly, the `object' approach makes sense as a way of organising any
 
1261
large, complicated program.
 
1262
 
 
1263
   The other key idea is communication.  One can visualise the program
 
1264
as being a large group of companies, constantly writing letters to each
 
1265
other to request information or ask for things to be done.  In a
 
1266
typical "message", one object A sends a detailed question or
 
1267
instruction to another object B, which replies with a simple answer.
 
1268
(Again, we've seen this already for routines: one routine calls
 
1269
another, and the other sends back a return value.)
 
1270
 
 
1271
Routines are only one of the four basic kinds of Inform object, which
 
1272
are:
 
1273
 
 
1274
 * routines, declared using [...];
 
1275
 
 
1276
 * strings in double-quotes "like so";
 
1277
 
 
1278
 * collections of routines and global variables, declared using Object;
 
1279
 
 
1280
 * prototypes for such collections, called "classes" and declared using Class.
 
1281
 
 
1282
These four kinds are called "metaclasses".  If O is an object, then the
 
1283
function
 
1284
 
 
1285
    metaclass(O)
 
1286
 
 
1287
will always tell you what kind it is, which will be one of the four
 
1288
values
 
1289
 
 
1290
    Routine   String   Object   Class
 
1291
 
 
1292
For example,
 
1293
 
 
1294
    metaclass("Violin Concerto no. 1")
 
1295
 
 
1296
evaluates to String, whereas
 
1297
 
 
1298
    metaclass(Main)
 
1299
 
 
1300
should always be Routine (since Main should always be the name of the
 
1301
routine where an Inform program begins to run).  From *Note Routines::
 
1302
we already know about metaclasses Routine and String, so it's the other
 
1303
two cases which this section will concentrate on.
 
1304
 
 
1305
!!!! Why only these four kinds?  Why are strings objects, and not (say)
 
1306
variables or dictionary words?  Object-oriented languages vary greatly
 
1307
in to what extreme they take the notion of object: in the dogmatic
 
1308
Smalltalk-80, every ingredient of any kind in a program is called an
 
1309
object: the program itself, the number 17, each variable and so on.
 
1310
Inform is much more moderate.  Routines, Objects and classes are
 
1311
genuinely object-like, and it just so happens that it's convenient to
 
1312
treat strings as objects (as we shall see).  But Inform stops there.
 
1313
 
 
1314
 
 
1315
File: inform,  Node: Object Tree,  Next: Creating Objects,  Prev: About Objects,  Up: Objects
 
1316
 
 
1317
Built-in functions 2: the object tree
 
1318
-------------------------------------
 
1319
 
 
1320
   Routines, strings and (as we shall see) classes are scattered about
 
1321
in an Inform program, in no particular order, and nothing links them
 
1322
together.  Object objects are special in that they are joined up in the
 
1323
"object tree" which grows through every Inform program.
 
1324
 
 
1325
   In this tree, objects have a kind of family relationship to each
 
1326
other: each one has a parent, a child and a sibling.  (The analogy here
 
1327
is with family trees.)  Normally such a relation is another object in
 
1328
the tree, but instead it can be
 
1329
 
 
1330
    nothing
 
1331
 
 
1332
which means "no object at all".  For example, consider the tree:
 
1333
 
 
1334
    Meadow
 
1335
      !
 
1336
    Mailbox  ->  Player
 
1337
      !            !
 
1338
    Note         Sceptre   ->   Cucumber  ->   Torch  ->   Magic Rod
 
1339
                                                 !
 
1340
                                               Battery
 
1341
 
 
1342
The Mailbox and Player are both children of the Meadow, which is their
 
1343
parent, but only the Mailbox is the child of the Meadow.  The Magic Rod
 
1344
is the sibling of the Torch, which is the sibling of the Cucumber, and
 
1345
so on.
 
1346
 
 
1347
Inform provides special functions for reading off positions in the tree:
 
1348
parent, sibling and child all do the obvious things, and in addition
 
1349
there's a function called children which counts up how many children an
 
1350
object has (where grandchildren don't count as children).  For instance,
 
1351
 
 
1352
    parent ( Mailbox )  == Meadow
 
1353
    children ( Player ) == 4
 
1354
    child ( Player )    == Sceptre
 
1355
    child ( Sceptre )   == nothing
 
1356
    sibling ( Torch )   == Magic Rod
 
1357
 
 
1358
It is a bad idea to apply these functions to the value nothing (since
 
1359
it is not an object, but a value representing the absence of one).  One
 
1360
can detect whether a quantity is a genuine object or not using
 
1361
metaclass, for
 
1362
 
 
1363
    metaclass(X)
 
1364
 
 
1365
is nothing for any value X which isn't an object: in particular,
 
1366
 
 
1367
    metaclass(nothing)  == nothing
 
1368
 
 
1369
!! Hopefully it's clear why the tree is useful for writing adventure
 
1370
games: it provides a way to simulate the vital idea of one thing being
 
1371
contained inside another.  But even in non-adventure game programs it
 
1372
can be a convenience.  For instance, it is an efficient way to hold
 
1373
tree structures and linked lists of information.