-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgrammers Guide
2305 lines (1714 loc) · 201 KB
/
Programmers Guide
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
LambdaMOO Programmer's Manual
For LambdaMOO Version 1.8.0p6
March 1997
by Pavel Curtis
aka Haakon
aka Lambda
Introduction
LambdaMOO is a network-accessible, multi-user, programmable, interactive system well-suited to the construction of text-based adventure games, conferencing systems, and other collaborative software. Its most common use, however, is as a multi-participant, low-bandwidth virtual reality, and it is with this focus in mind that I describe it here.
Participants (usually referred to as players) connect to LambdaMOO using Telnet or some other, more specialized, client program. Upon connection, they are usually presented with a welcome message explaining how to either create a new character or connect to an existing one. Characters are the embodiment of players in the virtual reality that is LambdaMOO.
Having connected to a character, players then give one-line commands that are parsed and interpreted by LambdaMOO as appropriate. Such commands may cause changes in the virtual reality, such as the location of a character, or may simply report on the current state of that reality, such as the appearance of some object.
The job of interpreting those commands is shared between the two major components in the LambdaMOO system: the server and the database. The server is a program, written in a standard programming language, that manages the network connections, maintains queues of commands and other tasks to be executed, controls all access to the database, and executes other programs written in the MOO programming language. The database contains representations of all the objects in the virtual reality, including the MOO programs that the server executes to give those objects their specific behaviors.
Almost every command is parsed by the server into a call on a MOO procedure, or verb, that actually does the work. Thus, programming in the MOO language is a central part of making non-trivial extensions to the database and thus, the virtual reality.
In the next chapter, I describe the structure and contents of a LambdaMOO database. The following chapter gives a complete description of how the server performs its primary duty: parsing the commands typed by players. Next, I describe the complete syntax and semantics of the MOO programming language. Finally, I describe all of the database conventions assumed by the server.
Note: This manual describes only those aspects of LambdaMOO that are entirely independent of the contents of the database. It does not describe, for example, the commands or programming interfaces present in the LambdaCore database.
The LambdaMOO Database
In this chapter, I begin by describing in detail the various kinds of data that can appear in a LambdaMOO database and that, therefore, MOO programs can manipulate. In a few places, I refer to the LambdaCore database. This is one particular LambdaMOO database, created every so often by extracting the "core" of the current database for the original LambdaMOO.
Note: The original LambdaMOO resides on the host lambda.parc.xerox.com (the numeric address for which is 192.216.54.2), on port 8888. Feel free to drop by! A copy of the most recent release of the LambdaCore database can be obtained by anonymous FTP from host ftp.parc.xerox.com in the directory pub/MOO.
MOO Value Types
There are only a few kinds of values that MOO programs can manipulate:
integers (in a specific, large range)
real numbers (represented with floating-point numbers)
strings (of characters)
objects (in the virtual reality)
errors (arising during program execution)
lists (of all of the above, including lists)
MOO supports the integers from -2^31 (that is, negative two to the power of 31) up to 2^31 - 1 (one less than two to the power of 31); that's from -2147483648 to 2147483647, enough for most purposes. In MOO programs, integers are written just as you see them here, an optional minus sign followed by a non-empty sequence of decimal digits. In particular, you may not put commas, periods, or spaces in the middle of large integers, as we sometimes do in English and other natural languages (e.g., `2,147,483,647').
Real numbers in MOO are represented as they are in almost all other programming languages, using so-called floating-point numbers. These have certain (large) limits on size and precision that make them useful for a wide range of applications. Floating-point numbers are written with an optional minus sign followed by a non-empty sequence of digits punctuated at some point with a decimal point (`.') and/or followed by a scientific-notation marker (the letter `E' or `e' followed by an optional sign and one or more digits). Here are some examples of floating-point numbers:
325.0 325. 3.25e2 0.325E3 325.E1 .0325e+4 32500e-2
All of these examples mean the same number. The third of these, as an example of scientific notation, should be read "3.25 times 10 to the power of 2".
Fine points: The MOO represents floating-point numbers using the local meaning of the C-language double type, which is almost always equivalent to IEEE 754 double precision floating point. If so, then the smallest positive floating-point number is no larger than 2.2250738585072014e-308 and the largest floating-point number is 1.7976931348623157e+308.
IEEE infinities and NaN values are not allowed in MOO. The error E_FLOAT is raised whenever an infinity would otherwise be computed; E_INVARG is raised whenever a NaN would otherwise arise. The value 0.0 is always returned on underflow.
Character strings are arbitrarily-long sequences of normal, ASCII printing characters. When written as values in a program, strings are enclosed in double-quotes, like this:
"This is a character string."
To include a double-quote in the string, precede it with a backslash (`\'), like this:
"His name was \"Leroy\", but nobody ever called him that."
Finally, to include a backslash in a string, double it:
"Some people use backslash ('\\') to mean set difference."
MOO strings may not include special ASCII characters like carriage-return, line-feed, bell, etc. The only non-printing characters allowed are spaces and tabs.
Fine point: There is a special kind of string used for representing the arbitrary bytes used in general, binary input and output. In a binary string, any byte that isn't an ASCII printing character or the space character is represented as the three-character substring "~XX", where XX is the hexadecimal representation of the byte; the input character `~' is represented by the three-character substring "~7E". This special representation is used by the functions encode_binary() and decode_binary() and by the functions notify() and read() with network connections that are in binary mode. See the descriptions of the set_connection_option(), encode_binary(), and decode_binary() functions for more details.
Objects are the backbone of the MOO database and, as such, deserve a great deal of discussion; the entire next section is devoted to them. For now, let it suffice to say that every object has a number, unique to that object. In programs, we write a reference to a particular object by putting a hash mark (`#') followed by the number, like this:
#495
Object numbers are always integers.
There are three special object numbers used for a variety of purposes: #-1, #-2, and #-3, usually referred to in the LambdaCore database as $nothing, $ambiguous_match, and $failed_match, respectively.
Errors are, by far, the least frequently used values in MOO. In the normal case, when a program attempts an operation that is erroneous for some reason (for example, trying to add a number to a character string), the server stops running the program and prints out an error message. However, it is possible for a program to stipulate that such errors should not stop execution; instead, the server should just let the value of the operation be an error value. The program can then test for such a result and take some appropriate kind of recovery action. In programs, error values are written as words beginning with `E_'. The complete list of error values, along with their associated messages, is as follows:
E_NONE No error
E_TYPE Type mismatch
E_DIV Division by zero
E_PERM Permission denied
E_PROPNF Property not found
E_VERBNF Verb not found
E_VARNF Variable not found
E_INVIND Invalid indirection
E_RECMOVE Recursive move
E_MAXREC Too many verb calls
E_RANGE Range error
E_ARGS Incorrect number of arguments
E_NACC Move refused by destination
E_INVARG Invalid argument
E_QUOTA Resource limit exceeded
E_FLOAT Floating-point arithmetic error
The final kind of value in MOO programs is lists. A list is a sequence of arbitrary MOO values, possibly including other lists. In programs, lists are written in mathematical set notation with each of the elements written out in order, separated by commas, the whole enclosed in curly braces (`{' and `}'). For example, a list of the names of the days of the week is written like this:
{"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}
Note that it doesn't matter that we put a line-break in the middle of the list. This is true in general in MOO: anywhere that a space can go, a line-break can go, with the same meaning. The only exception is inside character strings, where line-breaks are not allowed.
Objects in the MOO Database
Objects are, in a sense, the whole point of the MOO programming language. They are used to represent objects in the virtual reality, like people, rooms, exits, and other concrete things. Because of this, MOO makes a bigger deal out of creating objects than it does for other kinds of value, like integers.
Numbers always exist, in a sense; you have only to write them down in order to operate on them. With objects, it is different. The object with number `#958' does not exist just because you write down its number. An explicit operation, the `create()' function described later, is required to bring an object into existence. Symmetrically, once created, objects continue to exist until they are explicitly destroyed by the `recycle()' function (also described later).
The identifying number associated with an object is unique to that object. It was assigned when the object was created and will never be reused, even if the object is destroyed. Thus, if we create an object and it is assigned the number `#1076', the next object to be created will be assigned `#1077', even if `#1076' is destroyed in the meantime.
Every object is made up of three kinds of pieces that together define its behavior: attributes, properties, and verbs.
Fundamental Object Attributes
There are three fundamental attributes to every object:
A flag (either true or false) specifying whether or not the object represents a player,
The object that is its parent, and
A list of the objects that are its children; that is, those objects for which this object is their parent.
The act of creating a character sets the player attribute of an object and only a wizard (using the function set_player_flag()) can change that setting. Only characters have the player bit set to 1.
The parent/child hierarchy is used for classifying objects into general classes and then sharing behavior among all members of that class. For example, the LambdaCore database contains an object representing a sort of "generic" room. All other rooms are descendants (i.e., children or children's children, or ...) of that one. The generic room defines those pieces of behavior that are common to all rooms; other rooms specialize that behavior for their own purposes. The notion of classes and specialization is the very essence of what is meant by object-oriented programming. Only the functions create(), recycle(), chparent(), and renumber() can change the parent and children attributes.
Properties on Objects
A property is a named "slot" in an object that can hold an arbitrary MOO value. Every object has eight built-in properties whose values are constrained to be of particular types. In addition, an object can have any number of other properties, none of which have type constraints. The built-in properties are as follows:
name a string, the usual name for this object
owner an object, the player who controls access to it
location an object, where the object is in virtual reality
contents a list of objects, the inverse of `location'
programmer a bit, does the object have programmer rights?
wizard a bit, does the object have wizard rights?
r a bit, is the object publicly readable?
w a bit, is the object publicly writable?
f a bit, is the object fertile?
The `name' property is used to identify the object in various printed messages. It can only be set by a wizard or by the owner of the object. For player objects, the `name' property can only be set by a wizard; this allows the wizards, for example, to check that no two players have the same name.
The `owner' identifies the object that has owner rights to this object, allowing them, for example, to change the `name' property. Only a wizard can change the value of this property.
The `location' and `contents' properties describe a hierarchy of object containment in the virtual reality. Most objects are located "inside" some other object and that other object is the value of the `location' property. The `contents' property is a list of those objects for which this object is their location. In order to maintain the consistency of these properties, only the move() function is able to change them.
The `wizard' and `programmer' bits are only applicable to characters, objects representing players. They control permission to use certain facilities in the server. They may only be set by a wizard.
The `r' bit controls whether or not players other than the owner of this object can obtain a list of the properties or verbs in the object. Symmetrically, the `w' bit controls whether or not non-owners can add or delete properties and/or verbs on this object. The `r' and `w' bits can only be set by a wizard or by the owner of the object.
The `f' bit specifies whether or not this object is fertile, whether or not players other than the owner of this object can create new objects with this one as the parent. It also controls whether or not non-owners can use the chparent() built-in function to make this object the parent of an existing object. The `f' bit can only be set by a wizard or by the owner of the object.
All of the built-in properties on any object can, by default, be read by any player. It is possible, however, to override this behavior from within the database, making any of these properties readable only by wizards. See the chapter on server assumptions about the database for details.
As mentioned above, it is possible, and very useful, for objects to have other properties aside from the built-in ones. These can come from two sources.
First, an object has a property corresponding to every property in its parent object. To use the jargon of object-oriented programming, this is a kind of inheritance. If some object has a property named `foo', then so will all of its children and thus its children's children, and so on.
Second, an object may have a new property defined only on itself and its descendants. For example, an object representing a rock might have properties indicating its weight, chemical composition, and/or pointiness, depending upon the uses to which the rock was to be put in the virtual reality.
Every defined property (as opposed to those that are built-in) has an owner and a set of permissions for non-owners. The owner of the property can get and set the property's value and can change the non-owner permissions. Only a wizard can change the owner of a property.
The initial owner of a property is the player who added it; this is usually, but not always, the player who owns the object to which the property was added. This is because properties can only be added by the object owner or a wizard, unless the object is publicly writable (i.e., its `w' property is 1), which is rare. Thus, the owner of an object may not necessarily be the owner of every (or even any) property on that object.
The permissions on properties are drawn from this set: `r' (read), `w' (write), and `c' (change ownership in descendants). Read permission lets non-owners get the value of the property and, of course, write permission lets them set that value. The `c' permission bit is a little more complicated.
Recall that every object has all of the properties that its parent does and perhaps some more. Ordinarily, when a child object inherits a property from its parent, the owner of the child becomes the owner of that property. This is because the `c' permission bit is "on" by default. If the `c' bit is not on, then the inherited property has the same owner in the child as it does in the parent.
As an example of where this can be useful, the LambdaCore database ensures that every player has a `password' property containing the encrypted version of the player's connection password. For security reasons, we don't want other players to be able to see even the encrypted version of the password, so we turn off the `r' permission bit. To ensure that the password is only set in a consistent way (i.e., to the encrypted version of a player's password), we don't want to let anyone but a wizard change the property. Thus, in the parent object for all players, we made a wizard the owner of the password property and set the permissions to the empty string, "". That is, non-owners cannot read or write the property and, because the `c' bit is not set, the wizard who owns the property on the parent class also owns it on all of the descendants of that class.
Another, perhaps more down-to-earth example arose when a character named Ford started building objects he called "radios" and another character, yduJ, wanted to own one. Ford kindly made the generic radio object fertile, allowing yduJ to create a child object of it, her own radio. Radios had a property called `channel' that identified something corresponding to the frequency to which the radio was tuned. Ford had written nice programs on radios (verbs, discussed below) for turning the channel selector on the front of the radio, which would make a corresponding change in the value of the `channel' property. However, whenever anyone tried to turn the channel selector on yduJ's radio, they got a permissions error. The problem concerned the ownership of the `channel' property.
As I explain later, programs run with the permissions of their author. So, in this case, Ford's nice verb for setting the channel ran with his permissions. But, since the `channel' property in the generic radio had the `c' permission bit set, the `channel' property on yduJ's radio was owned by her. Ford didn't have permission to change it! The fix was simple. Ford changed the permissions on the `channel' property of the generic radio to be just `r', without the `c' bit, and yduJ made a new radio. This time, when yduJ's radio inherited the `channel' property, yduJ did not inherit ownership of it; Ford remained the owner. Now the radio worked properly, because Ford's verb had permission to change the channel.
Verbs on Objects
The final kind of piece making up an object is verbs. A verb is a named MOO program that is associated with a particular object. Most verbs implement commands that a player might type; for example, in the LambdaCore database, there is a verb on all objects representing containers that implements commands of the form `put object in container'. It is also possible for MOO programs to invoke the verbs defined on objects. Some verbs, in fact, are designed to be used only from inside MOO code; they do not correspond to any particular player command at all. Thus, verbs in MOO are like the `procedures' or `methods' found in some other programming languages.
As with properties, every verb has an owner and a set of permission bits. The owner of a verb can change its program, its permission bits, and its argument specifiers (discussed below). Only a wizard can change the owner of a verb. The owner of a verb also determines the permissions with which that verb runs; that is, the program in a verb can do whatever operations the owner of that verb is allowed to do and no others. Thus, for example, a verb owned by a wizard must be written very carefully, since wizards are allowed to do just about anything.
The permission bits on verbs are drawn from this set: `r' (read), `w' (write), `x' (execute), and `d' (debug). Read permission lets non-owners see the program for a verb and, symmetrically, write permission lets them change that program. The other two bits are not, properly speaking, permission bits at all; they have a universal effect, covering both the owner and non-owners.
The execute bit determines whether or not the verb can be invoked from within a MOO program (as opposed to from the command line, like the `put' verb on containers). If the `x' bit is not set, the verb cannot be called from inside a program. The `x' bit is usually set.
The setting of the debug bit determines what happens when the verb's program does something erroneous, like subtracting a number from a character string. If the `d' bit is set, then the server raises an error value; such raised errors can be caught by certain other pieces of MOO code. If the error is not caught, however, the server aborts execution of the command and, by default, prints an error message on the terminal of the player whose command is being executed. (See the chapter on server assumptions about the database for details on how uncaught errors are handled.) If the `d' bit is not set, then no error is raised, no message is printed, and the command is not aborted; instead the error value is returned as the result of the erroneous operation.
Note: the `d' bit exists only for historical reasons; it used to be the only way for MOO code to catch and handle errors. With the introduction of the try-except statement and the error-catching expression, the `d' bit is no longer useful. All new verbs should have the `d' bit set, using the newer facilities for error handling if desired. Over time, old verbs written assuming the `d' bit would not be set should be changed to use the new facilities instead.
In addition to an owner and some permission bits, every verb has three `argument specifiers', one each for the direct object, the preposition, and the indirect object. The direct and indirect specifiers are each drawn from this set: `this', `any', or `none'. The preposition specifier is `none', `any', or one of the items in this list:
with/using
at/to
in front of
in/inside/into
on top of/on/onto/upon
out of/from inside/from
over
through
under/underneath/beneath
behind
beside
for/about
is
as
off/off of
The argument specifiers are used in the process of parsing commands, described in the next chapter.
The Built-in Command Parser
The MOO server is able to do a small amount of parsing on the commands that a player enters. In particular, it can break apart commands that follow one of the following forms:
verb
verb direct-object
verb direct-object preposition indirect-object
Real examples of these forms, meaningful in the LambdaCore database, are as follows:
look
take yellow bird
put yellow bird in cuckoo clock
Note that English articles (i.e., `the', `a', and `an') are not generally used in MOO commands; the parser does not know that they are not important parts of objects' names.
To have any of this make real sense, it is important to understand precisely how the server decides what to do when a player types a command.
First, the server checks whether or not the first non-blank character in the command is one of the following:
" : ;
If so, that character is replaced by the corresponding command below, followed by a space:
say emote eval
For example, the command
"Hi, there.
is treated exactly as if it were as follows:
say Hi, there.
The server next breaks up the command into words. In the simplest case, the command is broken into words at every run of space characters; for example, the command `foo bar baz' would be broken into the words `foo', `bar', and `baz'. To force the server to include spaces in a "word", all or part of a word can be enclosed in double-quotes. For example, the command
foo "bar mumble" baz" "fr"otz" bl"o"rt
is broken into the words `foo', `bar mumble', `baz frotz', and `blort'. Finally, to include a double-quote or a backslash in a word, they can be preceded by a backslash, just like in MOO strings.
Having thus broken the string into words, the server next checks to see if the first word names any of the six "built-in" commands: `.program', `PREFIX', `OUTPUTPREFIX', `SUFFIX', `OUTPUTSUFFIX', or the connection's defined flush command, if any (`.flush' by default). The first one of these is only available to programmers, the next four are intended for use by client programs, and the last can vary from database to database or even connection to connection; all six are described in the final chapter of this document, "Server Commands and Database Assumptions". If the first word isn't one of the above, then we get to the usual case: a normal MOO command.
The server next gives code in the database a chance to handle the command. If the verb $do_command() exists, it is called with the words of the command passed as its arguments and argstr set to the raw command typed by the user. If $do_command() does not exist, or if that verb-call completes normally (i.e., without suspending or aborting) and returns a false value, then the built-in command parser is invoked to handle the command as described below. Otherwise, it is assumed that the database code handled the command completely and no further action is taken by the server for that command.
If the built-in command parser is invoked, the server tries to parse the command into a verb, direct object, preposition and indirect object. The first word is taken to be the verb. The server then tries to find one of the prepositional phrases listed at the end of the previous section, using the match that occurs earliest in the command. For example, in the very odd command `foo as bar to baz', the server would take `as' as the preposition, not `to'.
If the server succeeds in finding a preposition, it considers the words between the verb and the preposition to be the direct object and those after the preposition to be the indirect object. In both cases, the sequence of words is turned into a string by putting one space between each pair of words. Thus, in the odd command from the previous paragraph, there are no words in the direct object (i.e., it is considered to be the empty string, "") and the indirect object is "bar to baz".
If there was no preposition, then the direct object is taken to be all of the words after the verb and the indirect object is the empty string.
The next step is to try to find MOO objects that are named by the direct and indirect object strings.
First, if an object string is empty, then the corresponding object is the special object #-1 (aka $nothing in LambdaCore). If an object string has the form of an object number (i.e., a hash mark (`#') followed by digits), and the object with that number exists, then that is the named object. If the object string is either "me" or "here", then the player object itself or its location is used, respectively.
Otherwise, the server considers all of the objects whose location is either the player (i.e., the objects the player is "holding", so to speak) or the room the player is in (i.e., the objects in the same room as the player); it will try to match the object string against the various names for these objects.
The matching done by the server uses the `aliases' property of each of the objects it considers. The value of this property should be a list of strings, the various alternatives for naming the object. If it is not a list, or the object does not have an `aliases' property, then the empty list is used. In any case, the value of the `name' property is added to the list for the purposes of matching.
The server checks to see if the object string in the command is either exactly equal to or a prefix of any alias; if there are any exact matches, the prefix matches are ignored. If exactly one of the objects being considered has a matching alias, that object is used. If more than one has a match, then the special object #-2 (aka $ambiguous_match in LambdaCore) is used. If there are no matches, then the special object #-3 (aka $failed_match in LambdaCore) is used.
So, now the server has identified a verb string, a preposition string, and direct- and indirect-object strings and objects. It then looks at each of the verbs defined on each of the following four objects, in order:
the player who typed the command,
the room the player is in,
the direct object, if any, and
the indirect object, if any.
For each of these verbs in turn, it tests if all of the the following are true:
the verb string in the command matches one of the names for the verb,
the direct- and indirect-object values found by matching are allowed by the corresponding argument specifiers for the verb, and
the preposition string in the command is matched by the preposition specifier for the verb.
I'll explain each of these criteria in turn.
Every verb has one or more names; all of the names are kept in a single string, separated by spaces. In the simplest case, a verb-name is just a word made up of any characters other than spaces and stars (i.e., ` ' and `*'). In this case, the verb-name matches only itself; that is, the name must be matched exactly.
If the name contains a single star, however, then the name matches any prefix of itself that is at least as long as the part before the star. For example, the verb-name `foo*bar' matches any of the strings `foo', `foob', `fooba', or `foobar'; note that the star itself is not considered part of the name.
If the verb name ends in a star, then it matches any string that begins with the part before the star. For example, the verb-name `foo*' matches any of the strings `foo', `foobar', `food', or `foogleman', among many others. As a special case, if the verb-name is `*' (i.e., a single star all by itself), then it matches anything at all.
Recall that the argument specifiers for the direct and indirect objects are drawn from the set `none', `any', and `this'. If the specifier is `none', then the corresponding object value must be #-1 (aka $nothing in LambdaCore); that is, it must not have been specified. If the specifier is `any', then the corresponding object value may be anything at all. Finally, if the specifier is `this', then the corresponding object value must be the same as the object on which we found this verb; for example, if we are considering verbs on the player, then the object value must be the player object.
Finally, recall that the argument specifier for the preposition is either `none', `any', or one of several sets of prepositional phrases, given above. A specifier of `none' matches only if there was no preposition found in the command. A specifier of `any' always matches, regardless of what preposition was found, if any. If the specifier is a set of prepositional phrases, then the one found must be in that set for the specifier to match.
So, the server considers several objects in turn, checking each of their verbs in turn, looking for the first one that meets all of the criteria just explained. If it finds one, then that is the verb whose program will be executed for this command. If not, then it looks for a verb named `huh' on the room that the player is in; if one is found, then that verb will be called. This feature is useful for implementing room-specific command parsing or error recovery. If the server can't even find a `huh' verb to run, it prints an error message like `I couldn't understand that.' and the command is considered complete.
At long last, we have a program to run in response to the command typed by the player. When the code for the program begins execution, the following built-in variables will have the indicated values:
player an object, the player who typed the command
this an object, the object on which this verb was found
caller an object, the same as `player'
verb a string, the first word of the command
argstr a string, everything after the first word of the command
args a list of strings, the words in `argstr'
dobjstr a string, the direct object string found during parsing
dobj an object, the direct object value found during matching
prepstr a string, the prepositional phrase found during parsing
iobjstr a string, the indirect object string
iobj an object, the indirect object value
The value returned by the program, if any, is ignored by the server.
The MOO Programming Language
MOO stands for "MUD, Object Oriented." MUD, in turn, has been said to stand for many different things, but I tend to think of it as "Multi-User Dungeon" in the spirit of those ancient precursors to MUDs, Adventure and Zork.
MOO, the programming language, is a relatively small and simple object-oriented language designed to be easy to learn for most non-programmers; most complex systems still require some significant programming ability to accomplish, however.
Having given you enough context to allow you to understand exactly what MOO code is doing, I now explain what MOO code looks like and what it means. I begin with the syntax and semantics of expressions, those pieces of code that have values. After that, I cover statements, the next level of structure up from expressions. Next, I discuss the concept of a task, the kind of running process initiated by players entering commands, among other causes. Finally, I list all of the built-in functions available to MOO code and describe what they do.
First, though, let me mention comments. You can include bits of text in your MOO program that are ignored by the server. The idea is to allow you to put in notes to yourself and others about what the code is doing. To do this, begin the text of the comment with the two characters `/*' and end it with the two characters `*/'; this is just like comments in the C programming language. Note that the server will completely ignore that text; it will not be saved in the database. Thus, such comments are only useful in files of code that you maintain outside the database.
To include a more persistent comment in your code, try using a character string literal as a statement. For example, the sentence about peanut butter in the following code is essentially ignored during execution but will be maintained in the database:
for x in (players())
"Grendel eats peanut butter!";
player:tell(x.name, " (", x, ")");
endfor
MOO Language Expressions
Expressions are those pieces of MOO code that generate values; for example, the MOO code
3 + 4
is an expression that generates (or "has" or "returns") the value 7. There are many kinds of expressions in MOO, all of them discussed below.
Errors While Evaluating Expressions
Most kinds of expressions can, under some circumstances, cause an error to be generated. For example, the expression x / y will generate the error E_DIV if y is equal to zero. When an expression generates an error, the behavior of the server is controlled by setting of the `d' (debug) bit on the verb containing that expression. If the `d' bit is not set, then the error is effectively squelched immediately upon generation; the error value is simply returned as the value of the expression that generated it.
Note: this error-squelching behavior is very error prone, since it affects all errors, including ones the programmer may not have anticipated. The `d' bit exists only for historical reasons; it was once the only way for MOO programmers to catch and handle errors. The error-catching expression and the try-except statement, both described below, are far better ways of accomplishing the same thing.
If the `d' bit is set, as it usually is, then the error is raised and can be caught and handled either by code surrounding the expression in question or by verbs higher up on the chain of calls leading to the current verb. If the error is not caught, then the server aborts the entire task and, by default, prints a message to the current player. See the descriptions of the error-catching expression and the try-except statement for the details of how errors can be caught, and the chapter on server assumptions about the database for details on the handling of uncaught errors.
Writing Values Directly in Verbs
The simplest kind of expression is a literal MOO value, just as described in the section on values at the beginning of this document. For example, the following are all expressions:
17
#893
"This is a character string."
E_TYPE
{"This", "is", "a", "list", "of", "words"}
In the case of lists, like the last example above, note that the list expression contains other expressions, several character strings in this case. In general, those expressions can be of any kind at all, not necessarily literal values. For example,
{3 + 4, 3 - 4, 3 * 4}
is an expression whose value is the list {7, -1, 12}.
Naming Values Within a Verb
As discussed earlier, it is possible to store values in properties on objects; the properties will keep those values forever, or until another value is explicitly put there. Quite often, though, it is useful to have a place to put a value for just a little while. MOO provides local variables for this purpose.
Variables are named places to hold values; you can get and set the value in a given variable as many times as you like. Variables are temporary, though; they only last while a particular verb is running; after it finishes, all of the variables given values there cease to exist and the values are forgotten.
Variables are also "local" to a particular verb; every verb has its own set of them. Thus, the variables set in one verb are not visible to the code of other verbs.
The name for a variable is made up entirely of letters, digits, and the underscore character (`_') and does not begin with a digit. The following are all valid variable names:
foo
_foo
this2that
M68000
two_words
This_is_a_very_long_multiword_variable_name
Note that, along with almost everything else in MOO, the case of the letters in variable names is insignificant. For example, these are all names for the same variable:
fubar
Fubar
FUBAR
fUbAr
A variable name is itself an expression; its value is the value of the named variable. When a verb begins, almost no variables have values yet; if you try to use the value of a variable that doesn't have one, the error value E_VARNF is raised. (MOO is unlike many other programming languages in which one must `declare' each variable before using it; MOO has no such declarations.) The following variables always have values:
INT FLOAT OBJ
STR LIST ERR
player this caller
verb args argstr
dobj dobjstr prepstr
iobj iobjstr NUM
The values of some of these variables always start out the same:
INT
an integer, the type code for integers (see the description of the function typeof(), below)
NUM
the same as INT (for historical reasons)
FLOAT
an integer, the type code for floating-point numbers
LIST
an integer, the type code for lists
STR
an integer, the type code for strings
OBJ
an integer, the type code for objects
ERR
an integer, the type code for error values
For others, the general meaning of the value is consistent, though the value itself is different for different situations:
player
an object, the player who typed the command that started the task that involved running this piece of code.
this
an object, the object on which the currently-running verb was found.
caller
an object, the object on which the verb that called the currently-running verb was found. For the first verb called for a given command, `caller' has the same value as `player'.
verb
a string, the name by which the currently-running verb was identified.
args
a list, the arguments given to this verb. For the first verb called for a given command, this is a list of strings, the words on the command line.
The rest of the so-called "built-in" variables are only really meaningful for the first verb called for a given command. Their semantics is given in the discussion of command parsing, above.
To change what value is stored in a variable, use an assignment expression:
variable = expression
For example, to change the variable named `x' to have the value 17, you would write `x = 17' as an expression. An assignment expression does two things:
it changes the value of of the named variable, and
it returns the new value of that variable.
Thus, the expression
13 + (x = 17)
changes the value of `x' to be 17 and returns 30.
Arithmetic Operators
All of the usual simple operations on numbers are available to MOO programs:
+ - * / %
These are, in order, addition, subtraction, multiplication, division, and remainder. In the following table, the expressions on the left have the corresponding values on the right:
5 + 2 => 7
5 - 2 => 3
5 * 2 => 10
5 / 2 => 2
5.0 / 2.0 => 2.5
5 % 2 => 1
5.0 % 2.0 => 1.0
5 % -2 => 1
-5 % 2 => -1
-5 % -2 => -1
-(5 + 2) => -7
Note that integer division in MOO throws away the remainder and that the result of the remainder operator (`%') has the same sign as the left-hand operand. Also, note that `-' can be used without a left-hand operand to negate a numeric expression.
Fine point: Integers and floating-point numbers cannot be mixed in any particular use of these arithmetic operators; unlike some other programming languages, MOO does not automatically coerce integers into floating-point numbers. You can use the tofloat() function to perform an explicit conversion.
The `+' operator can also be used to append two strings. The expression
"foo" + "bar"
has the value
"foobar"
Unless both operands to an arithmetic operator are numbers of the same kind (or, for `+', both strings), the error value E_TYPE is raised. If the right-hand operand for the division or remainder operators (`/' or `%') is zero, the error value E_DIV is raised.
MOO also supports the exponentiation operation, also known as "raising to a power," using the `^' operator:
3 ^ 4 => 81
3 ^ 4.5 error--> E_TYPE
3.5 ^ 4 => 150.0625
3.5 ^ 4.5 => 280.741230801382
Note that if the first operand is an integer, then the second operand must also be an integer. If the first operand is a floating-point number, then the second operand can be either kind of number. Although it is legal to raise an integer to a negative power, it is unlikely to be terribly useful.
Comparing Values
Any two values can be compared for equality using `==' and `!='. The first of these returns 1 if the two values are equal and 0 otherwise; the second does the reverse:
3 == 4 => 0
3 != 4 => 1
3 == 3.0 => 0
"foo" == "Foo" => 1
#34 != #34 => 0
{1, #34, "foo"} == {1, #34, "FoO"} => 1
E_DIV == E_TYPE => 0
3 != "foo" => 1
Note that integers and floating-point numbers are never equal to one another, even in the `obvious' cases. Also note that comparison of strings (and list values containing strings) is case-insensitive; that is, it does not distinguish between the upper- and lower-case version of letters. To test two values for case-sensitive equality, use the `equal' function described later.
Warning: It is easy (and very annoying) to confuse the equality-testing operator (`==') with the assignment operator (`='), leading to nasty, hard-to-find bugs. Don't do this.
Numbers, object numbers, strings, and error values can also be compared for ordering purposes using the following operators:
< <= >= >
meaning "less than," "less than or equal," "greater than or equal," and "greater than," respectively. As with the equality operators, these return 1 when their operands are in the appropriate relation and 0 otherwise:
3 < 4 => 1
3 < 4.0 error--> E_TYPE
#34 >= #32 => 1
"foo" <= "Boo" => 0
E_DIV > E_TYPE => 1
Note that, as with the equality operators, strings are compared case-insensitively. To perform a case-sensitive string comparison, use the `strcmp' function described later. Also note that the error values are ordered as given in the table in the section on values. If the operands to these four comparison operators are of different types (even integers and floating-point numbers are considered different types), or if they are lists, then E_TYPE is raised.
Values as True and False
There is a notion in MOO of true and false values; every value is one or the other. The true values are as follows:
all integers other than zero,
all floating-point numbers not equal to 0.0,
all non-empty strings (i.e., other than `""'), and
all non-empty lists (i.e., other than `{}').
All other values are false:
the integer zero,
the floating-point numbers 0.0 and -0.0,
the empty string (`""'),
the empty list (`{}'),
all object numbers, and
all error values.
There are four kinds of expressions and two kinds of statements that depend upon this classification of MOO values. In describing them, I sometimes refer to the truth value of a MOO value; this is just true or false, the category into which that MOO value is classified.
The conditional expression in MOO has the following form:
expression-1 ? expression-2 | expression-3
First, expression-1 is evaluated. If it returns a true value, then expression-2 is evaluated and whatever it returns is returned as the value of the conditional expression as a whole. If expression-1 returns a false value, then expression-3 is evaluated instead and its value is used as that of the conditional expression.
1 ? 2 | 3 => 2
0 ? 2 | 3 => 3
"foo" ? 17 | {#34} => 17
Note that only one of expression-2 and expression-3 is evaluated, never both.
To negate the truth value of a MOO value, use the `!' operator:
! expression
If the value of expression is true, `!' returns 0; otherwise, it returns 1:
! "foo" => 0
! (3 >= 4) => 1
The negation operator is usually read as "not."
It is frequently useful to test more than one condition to see if some or all of them are true. MOO provides two operators for this:
expression-1 && expression-2
expression-1 || expression-2
These operators are usually read as "and" and "or," respectively.
The `&&' operator first evaluates expression-1. If it returns a true value, then expression-2 is evaluated and its value becomes the value of the `&&' expression as a whole; otherwise, the value of expression-1 is used as the value of the `&&' expression. Note that expression-2 is only evaluated if expression-1 returns a true value. The `&&' expression is equivalent to the conditional expression
expression-1 ? expression-2 | expression-1
except that expression-1 is only evaluated once.
The `||' operator works similarly, except that expression-2 is evaluated only if expression-1 returns a false value. It is equivalent to the conditional expression
expression-1 ? expression-1 | expression-2
except that, as with `&&', expression-1 is only evaluated once.
These two operators behave very much like "and" and "or" in English:
1 && 1 => 1
0 && 1 => 0
0 && 0 => 0
1 || 1 => 1
0 || 1 => 1
0 || 0 => 0
17 <= 23 && 23 <= 27 => 1
Indexing into Lists and Strings
Both strings and lists can be seen as ordered sequences of MOO values. In the case of strings, each is a sequence of single-character strings; that is, one can view the string "bar" as a sequence of the strings "b", "a", and "r". MOO allows you to refer to the elements of lists and strings by number, by the index of that element in the list or string. The first element in a list or string has index 1, the second has index 2, and so on.
Extracting an Element from a List or String
The indexing expression in MOO extracts a specified element from a list or string:
expression-1[expression-2]
First, expression-1 is evaluated; it must return a list or a string (the sequence). Then, expression-2 is evaluated and must return an integer (the index). If either of the expressions returns some other type of value, E_TYPE is returned. The index must be between 1 and the length of the sequence, inclusive; if it is not, then E_RANGE is raised. The value of the indexing expression is the index'th element in the sequence. Anywhere within expression-2, you can use the symbol $ as an expression returning the length of the value of expression-1.
"fob"[2] => "o"
"fob"[1] => "f"
{#12, #23, #34}[$ - 1] => #23
Note that there are no legal indices for the empty string or list, since there are no integers between 1 and 0 (the length of the empty string or list).
Fine point: The $ expression actually returns the length of the value of the expression just before the nearest enclosing [...] indexing or subranging brackets. For example:
"frob"[{3, 2, 4}[$]] => "b"
Replacing an Element of a List or String
It often happens that one wants to change just one particular slot of a list or string, which is stored in a variable or a property. This can be done conveniently using an indexed assignment having one of the following forms:
variable[index-expr] = result-expr
object-expr.name[index-expr] = result-expr
object-expr.(name-expr)[index-expr] = result-expr
$name[index-expr] = result-expr
The first form writes into a variable, and the last three forms write into a property. The usual errors (E_TYPE, E_INVIND, E_PROPNF and E_PERM for lack of read/write permission on the property) may be raised, just as in reading and writing any object property; see the discussion of object property expressions below for details. Correspondingly, if variable does not yet have a value (i.e., it has never been assigned to), E_VARNF will be raised.
If index-expr is not an integer, or if the value of variable or the property is not a list or string, E_TYPE is raised. If result-expr is a string, but not of length 1, E_INVARG is raised. Now suppose index-expr evaluates to an integer k. If k is outside the range of the list or string (i.e. smaller than 1 or greater than the length of the list or string), E_RANGE is raised. Otherwise, the actual assignment takes place. For lists, the variable or the property is assigned a new list that is identical to the original one except at the k-th position, where the new list contains the result of result-expr instead. For strings, the variable or the property is assigned a new string that is identical to the original one, except the k-th character is changed to be result-expr.
The assignment expression itself returns the value of result-expr. For the following examples, assume that l initially contains the list {1, 2, 3} and that s initially contains the string "foobar":
l[5] = 3 error--> E_RANGE
l["first"] = 4 error--> E_TYPE
s[3] = "baz" error--> E_INVARG
l[2] = l[2] + 3 => 5
l => {1, 5, 3}
l[2] = "foo" => "foo"
l => {1, "foo", 3}
s[2] = "u" => "u"
s => "fuobar"
s[$] = "z" => "z"
s => "fuobaz"
Note that the $ expression may also be used in indexed assignments with the same meaning as before.
Fine point: After an indexed assignment, the variable or property contains a new list or string, a copy of the original list in all but the k-th place, where it contains a new value. In programming-language jargon, the original list is not mutated, and there is no aliasing. (Indeed, no MOO value is mutable and no aliasing ever occurs.)
In the list case, indexed assignment can be nested to many levels, to work on nested lists. Assume that l initially contains the list
{{1, 2, 3}, {4, 5, 6}, "foo"}
in the following examples:
l[7] = 4 error--> E_RANGE
l[1][8] = 35 error--> E_RANGE
l[3][2] = 7 error--> E_TYPE
l[1][1][1] = 3 error--> E_TYPE
l[2][2] = -l[2][2] => -5
l => {{1, 2, 3}, {4, -5, 6}, "foo"}
l[2] = "bar" => "bar"
l => {{1, 2, 3}, "bar", "foo"}
l[2][$] = "z" => "z"
l => {{1, 2, 3}, "baz", "foo"}
The first two examples raise E_RANGE because 7 is out of the range of l and 8 is out of the range of l[1]. The next two examples raise E_TYPE because l[3] and l[1][1] are not lists.
Extracting a Subsequence of a List or String
The range expression extracts a specified subsequence from a list or string:
expression-1[expression-2..expression-3]
The three expressions are evaluated in order. Expression-1 must return a list or string (the sequence) and the other two expressions must return integers (the low and high indices, respectively); otherwise, E_TYPE is raised. The $ expression can be used in either or both of expression-2 and expression-3 just as before, meaning the length of the value of expression-1.
If the low index is greater than the high index, then the empty string or list is returned, depending on whether the sequence is a string or a list. Otherwise, both indices must be between 1 and the length of the sequence; E_RANGE is raised if they are not. A new list or string is returned that contains just the elements of the sequence with indices between the low and high bounds.
"foobar"[2..$] => "oobar"
"foobar"[3..3] => "o"
"foobar"[17..12] => ""
{"one", "two", "three"}[$ - 1..$] => {"two", "three"}
{"one", "two", "three"}[3..3] => {"three"}
{"one", "two", "three"}[17..12] => {}
Replacing a Subsequence of a List or String
The subrange assigment replaces a specified subsequence of a list or string with a supplied subsequence. The allowed forms are:
variable[start-index-expr..end-index-expr] = result-expr
object-expr.name[start-index-expr..end-index-expr] = result-expr
object-expr.(name-expr)[start-index-expr..end-index-expr] = result-expr
$name[start-index-expr..end-index-expr] = result-expr
As with indexed assigments, the first form writes into a variable, and the last three forms write into a property. The same errors (E_TYPE, E_INVIND, E_PROPNF and E_PERM for lack of read/write permission on the property) may be raised. If variable does not yet have a value (i.e., it has never been assigned to), E_VARNF will be raised. As before, the $ expression can be used in either start-index-expr or end-index-expr, meaning the length of the original value of the expression just before the [...] part.
If start-index-expr or end-index-expr is not an integer, if the value of variable or the property is not a list or string, or result-expr is not the same type as variable or the property, E_TYPE is raised. E_RANGE is raised if end-index-expr is less than zero or if start-index-expr is greater than the length of the list or string plus one. Note: the length of result-expr does not need to be the same as the length of the specified range.
In precise terms, the subrange assigment
v[start..end] = value
is equivalent to
v = {@v[1..start - 1], @value, @v[end + 1..$]}
if v is a list and to
v = v[1..start - 1] + value + v[end + 1..$]
if v is a string.
The assigment expression itself returns the value of result-expr. For the following examples, assume that l initially contains the list {1, 2, 3} and that s initially contains the string "foobar":
l[5..6] = {7, 8} error--> E_RANGE
l[2..3] = 4 error--> E_TYPE
l[#2..3] = {7} error--> E_TYPE
s[2..3] = {6} error--> E_TYPE
l[2..3] = {6, 7, 8, 9} => {6, 7, 8, 9}
l => {1, 6, 7, 8, 9}
l[2..1] = {10, "foo"} => {10, "foo"}
l => {1, 10, "foo", 6, 7, 8, 9}
l[3][2..$] = "u" => "u"
l => {1, 10, "fu", 6, 7, 8, 9}
s[7..12] = "baz" => "baz"
s => "foobarbaz"
s[1..3] = "fu" => "fu"
s => "fubarbaz"
s[1..0] = "test" => "test"
s => "testfubarbaz"
Other Operations on Lists
As was mentioned earlier, lists can be constructed by writing a comma-separated sequence of expressions inside curly braces:
{expression-1, expression-2, ..., expression-N}
The resulting list has the value of expression-1 as its first element, that of expression-2 as the second, etc.
{3 < 4, 3 <= 4, 3 >= 4, 3 > 4} => {1, 1, 0, 0}
Additionally, one may precede any of these expressions by the splicing operator, `@'. Such an expression must return a list; rather than the old list itself becoming an element of the new list, all of the elements of the old list are included in the new list. This concept is easy to understand, but hard to explain in words, so here are some examples. For these examples, assume that the variable a has the value {2, 3, 4} and that b has the value {"Foo", "Bar"}:
{1, a, 5} => {1, {2, 3, 4}, 5}
{1, @a, 5} => {1, 2, 3, 4, 5}
{a, @a} => {{2, 3, 4}, 2, 3, 4}
{@a, @b} => {2, 3, 4, "Foo", "Bar"}
If the splicing operator (`@') precedes an expression whose value is not a list, then E_TYPE is raised as the value of the list construction as a whole.
The list membership expression tests whether or not a given MOO value is an element of a given list and, if so, with what index:
expression-1 in expression-2
Expression-2 must return a list; otherwise, E_TYPE is raised. If the value of expression-1 is in that list, then the index of its first occurrence in the list is returned; otherwise, the `in' expression returns 0.
2 in {5, 8, 2, 3} => 3
7 in {5, 8, 2, 3} => 0
"bar" in {"Foo", "Bar", "Baz"} => 2
Note that the list membership operator is case-insensitive in comparing strings, just like the comparison operators. To perform a case-sensitive list membership test, use the `is_member' function described later. Note also that since it returns zero only if the given value is not in the given list, the `in' expression can be used either as a membership test or as an element locator.
Spreading List Elements Among Variables
It is often the case in MOO programming that you will want to access the elements of a list individually, with each element stored in a separate variables. This desire arises, for example, at the beginning of almost every MOO verb, since the arguments to all verbs are delivered all bunched together in a single list. In such circumstances, you could write statements like these:
first = args[1];
second = args[2];
if (length(args) > 2)
third = args[3];
else
third = 0;
endif
This approach gets pretty tedious, both to read and to write, and it's prone to errors if you mistype one of the indices. Also, you often want to check whether or not any extra list elements were present, adding to the tedium.
MOO provides a special kind of assignment expression, called scattering assignment made just for cases such as these. A scattering assignment expression looks like this:
{target, ...} = expr
where each target describes a place to store elements of the list that results from evaluating expr. A target has one of the following forms:
variable
This is the simplest target, just a simple variable; the list element in the corresponding position is assigned to the variable. This is called a required target, since the assignment is required to put one of the list elements into the variable.
?variable
This is called an optional target, since it doesn't always get assigned an element. If there are any list elements left over after all of the required targets have been accounted for (along with all of the other optionals to the left of this one), then this variable is treated like a required one and the list element in the corresponding position is assigned to the variable. If there aren't enough elements to assign one to this target, then no assignment is made to this variable, leaving it with whatever its previous value was.
?variable = default-expr
This is also an optional target, but if there aren't enough list elements available to assign one to this target, the result of evaluating default-expr is assigned to it instead. Thus, default-expr provides a default value for the variable. The default value expressions are evaluated and assigned working from left to right after all of the other assignments have been performed.
@variable
By analogy with the @ syntax in list construction, this variable is assigned a list of all of the `leftover' list elements in this part of the list after all of the other targets have been filled in. It is assigned the empty list if there aren't any elements left over. This is called a rest target, since it gets the rest of the elements. There may be at most one rest target in each scattering assignment expression.
If there aren't enough list elements to fill all of the required targets, or if there are more than enough to fill all of the required and optional targets but there isn't a rest target to take the leftover ones, then E_ARGS is raised.
Here are some examples of how this works. Assume first that the verb me:foo() contains the following code:
b = c = e = 17;
{a, ?b, ?c = 8, @d, ?e = 9, f} = args;
return {a, b, c, d, e, f};
Then the following calls return the given values:
me:foo(1) error--> E_ARGS
me:foo(1, 2) => {1, 17, 8, {}, 9, 2}
me:foo(1, 2, 3) => {1, 2, 8, {}, 9, 3}
me:foo(1, 2, 3, 4) => {1, 2, 3, {}, 9, 4}
me:foo(1, 2, 3, 4, 5) => {1, 2, 3, {}, 4, 5}
me:foo(1, 2, 3, 4, 5, 6) => {1, 2, 3, {4}, 5, 6}
me:foo(1, 2, 3, 4, 5, 6, 7) => {1, 2, 3, {4, 5}, 6, 7}
me:foo(1, 2, 3, 4, 5, 6, 7, 8) => {1, 2, 3, {4, 5, 6}, 7, 8}
Using scattering assignment, the example at the begining of this section could be rewritten more simply, reliably, and readably:
{first, second, ?third = 0} = args;
It is good MOO programming style to use a scattering assignment at the top of nearly every verb, since it shows so clearly just what kinds of arguments the verb expects.
Getting and Setting the Values of Properties
Usually, one can read the value of a property on an object with a simple expression:
expression.name
Expression must return an object number; if not, E_TYPE is raised. If the object with that number does not exist, E_INVIND is raised. Otherwise, if the object does not have a property with that name, then E_PROPNF is raised. Otherwise, if the named property is not readable by the owner of the current verb, then E_PERM is raised. Finally, assuming that none of these terrible things happens, the value of the named property on the given object is returned.
I said "usually" in the paragraph above because that simple expression only works if the name of the property obeys the same rules as for the names of variables (i.e., consists entirely of letters, digits, and underscores, and doesn't begin with a digit). Property names are not restricted to this set, though. Also, it is sometimes useful to be able to figure out what property to read by some computation. For these more general uses, the following syntax is also allowed:
expression-1.(expression-2)
As before, expression-1 must return an object number. Expression-2 must return a string, the name of the property to be read; E_TYPE is raised otherwise. Using this syntax, any property can be read, regardless of its name.
Note that, as with almost everything in MOO, case is not significant in the names of properties. Thus, the following expressions are all equivalent:
foo.bar
foo.Bar
foo.("bAr")
The LambdaCore database uses several properties on #0, the system object, for various special purposes. For example, the value of #0.room is the "generic room" object, #0.exit is the "generic exit" object, etc. This allows MOO programs to refer to these useful objects more easily (and more readably) than using their object numbers directly. To make this usage even easier and more readable, the expression
$name
(where name obeys the rules for variable names) is an abbreviation for
#0.name
Thus, for example, the value $nothing mentioned earlier is really #-1, the value of #0.nothing.
As with variables, one uses the assignment operator (`=') to change the value of a property. For example, the expression
14 + (#27.foo = 17)
changes the value of the `foo' property of the object numbered 27 to be 17 and then returns 31. Assignments to properties check that the owner of the current verb has write permission on the given property, raising E_PERM otherwise. Read permission is not required.
Calling Built-in Functions and Other Verbs
MOO provides a large number of useful functions for performing a wide variety of operations; a complete list, giving their names, arguments, and semantics, appears in a separate section later. As an example to give you the idea, there is a function named `length' that returns the length of a given string or list.
The syntax of a call to a function is as follows:
name(expr-1, expr-2, ..., expr-N)
where name is the name of one of the built-in functions. The expressions between the parentheses, called arguments, are each evaluated in turn and then given to the named function to use in its appropriate way. Most functions require that a specific number of arguments be given; otherwise, E_ARGS is raised. Most also require that certain of the arguments have certain specified types (e.g., the length() function requires a list or a string as its argument); E_TYPE is raised if any argument has the wrong type.
As with list construction, the splicing operator `@' can precede any argument expression. The value of such an expression must be a list; E_TYPE is raised otherwise. The elements of this list are passed as individual arguments, in place of the list as a whole.
Verbs can also call other verbs, usually using this syntax:
expr-0:name(expr-1, expr-2, ..., expr-N)
Expr-0 must return an object number; E_TYPE is raised otherwise. If the object with that number does not exist, E_INVIND is raised. If this task is too deeply nested in verbs calling verbs calling verbs, then E_MAXREC is raised; the default limit is 50 levels, but this can be changed from within the database; see the chapter on server assumptions about the database for details. If neither the object nor any of its ancestors defines a verb matching the given name, E_VERBNF is raised. Otherwise, if none of these nasty things happens, the named verb on the given object is called; the various built-in variables have the following initial values in the called verb:
this
an object, the value of expr-0
verb
a string, the name used in calling this verb
args
a list, the values of expr-1, expr-2, etc.
caller
an object, the value of this in the calling verb
player
an object, the same value as it had initially in the calling verb or, if the calling verb is running with wizard permissions, the same as the current value in the calling verb.
All other built-in variables (argstr, dobj, etc.) are initialized with the same values they have in the calling verb.
As with the discussion of property references above, I said "usually" at the beginning of the previous paragraph because that syntax is only allowed when the name follows the rules for allowed variable names. Also as with property reference, there is a syntax allowing you to compute the name of the verb:
expr-0:(expr-00)(expr-1, expr-2, ..., expr-N)
The expression expr-00 must return a string; E_TYPE is raised otherwise.
The splicing operator (`@') can be used with verb-call arguments, too, just as with the arguments to built-in functions.
In many databases, a number of important verbs are defined on #0, the system object. As with the `$foo' notation for properties on #0, the server defines a special syntax for calling verbs on #0:
$name(expr-1, expr-2, ..., expr-N)
(where name obeys the rules for variable names) is an abbreviation for
#0:name(expr-1, expr-2, ..., expr-N)
Catching Errors in Expressions
It is often useful to be able to catch an error that an expression raises, to keep the error from aborting the whole task, and to keep on running as if the expression had returned some other value normally. The following expression accomplishes this:
` expr-1 ! codes => expr-2 '
Note: the open- and close-quotation marks in the previous line are really part of the syntax; you must actually type them as part of your MOO program for this kind of expression.
The codes part is either the keyword ANY or else a comma-separated list of expressions, just like an argument list. As in an argument list, the splicing operator (`@') can be used here. The => expr-2 part of the error-catching expression is optional.
First, the codes part is evaluated, yielding a list of error codes that should be caught if they're raised; if codes is ANY, then it is equivalent to the list of all possible MOO values.
Next, expr-1 is evaluated. If it evaluates normally, without raising an error, then its value becomes the value of the entire error-catching expression. If evaluating expr-1 results in an error being raised, then call that error E. If E is in the list resulting from evaluating codes, then E is considered caught by this error-catching expression. In such a case, if expr-2 was given, it is evaluated to get the outcome of the entire error-catching expression; if expr-2 was omitted, then E becomes the value of the entire expression. If E is not in the list resulting from codes, then this expression does not catch the error at all and it continues to be raised, possibly to be caught by some piece of code either surrounding this expression or higher up on the verb-call stack.
Here are some examples of the use of this kind of expression:
`x + 1 ! E_TYPE => 0'
Returns x + 1 if x is an integer, returns 0 if x is not an integer, and raises E_VARNF if x doesn't have a value.
`x.y ! E_PROPNF, E_PERM => 17'
Returns x.y if that doesn't cause an error, 17 if x doesn't have a y property or that property isn't readable, and raises some other kind of error (like E_INVIND) if x.y does.
`1 / 0 ! ANY'
Returns E_DIV.
Parentheses and Operator Precedence
As shown in a few examples above, MOO allows you to use parentheses to make it clear how you intend for complex expressions to be grouped. For example, the expression
3 * (4 + 5)
performs the addition of 4 and 5 before multiplying the result by 3.
If you leave out the parentheses, MOO will figure out how to group the expression according to certain rules. The first of these is that some operators have higher precedence than others; operators with higher precedence will more tightly bind to their operands than those with lower precedence. For example, multiplication has higher precedence than addition; thus, if the parentheses had been left out of the expression in the previous paragraph, MOO would have grouped it as follows:
(3 * 4) + 5
The table below gives the relative precedence of all of the MOO operators; operators on higher lines in the table have higher precedence and those on the same line have identical precedence:
! - (without a left operand)
^
* / %
+ -
== != < <= > >= in
&& ||
... ? ... | ... (the conditional expression)
=
Thus, the horrendous expression
x = a < b && c > d + e * f ? w in y | - q - r
would be grouped as follows:
x = (((a < b) && (c > (d + (e * f)))) ? (w in y) | ((- q) - r))
It is best to keep expressions simpler than this and to use parentheses liberally to make your meaning clear to other humans.
MOO Language Statements
Statements are MOO constructs that, in contrast to expressions, perform some useful, non-value-producing operation. For example, there are several kinds of statements, called `looping constructs', that repeatedly perform some set of operations. Fortunately, there are many fewer kinds of statements in MOO than there are kinds of expressions.
Errors While Executing Statements
Statements do not return values, but some kinds of statements can, under certain circumstances described below, generate errors. If such an error is generated in a verb whose `d' (debug) bit is not set, then the error is ignored and the statement that generated it is simply skipped; execution proceeds with the next statement.
Note: this error-ignoring behavior is very error prone, since it affects all errors, including ones the programmer may not have anticipated. The `d' bit exists only for historical reasons; it was once the only way for MOO programmers to catch and handle errors. The error-catching expression and the try-except statement are far better ways of accomplishing the same thing.
If the `d' bit is set, as it usually is, then the error is raised and can be caught and handled either by code surrounding the expression in question or by verbs higher up on the chain of calls leading to the current verb. If the error is not caught, then the server aborts the entire task and, by default, prints a message to the current player. See the descriptions of the error-catching expression and the try-except statement for the details of how errors can be caught, and the chapter on server assumptions about the database for details on the handling of uncaught errors.
Simple Statements
The simplest kind of statement is the null statement, consisting of just a semicolon:
;
It doesn't do anything at all, but it does it very quickly.
The next simplest statement is also one of the most common, the expression statement, consisting of any expression followed by a semicolon:
expression;
The given expression is evaluated and the resulting value is ignored. Commonly-used kinds of expressions for such statements include assignments and verb calls. Of course, there's no use for such a statement unless the evaluation of expression has some side-effect, such as changing the value of some variable or property, printing some text on someone's screen, etc.
Statements for Testing Conditions
The `if' statement allows you to decide whether or not to perform some statements based on the value of an arbitrary expression:
if (expression)
statements
endif
Expression is evaluated and, if it returns a true value, the statements are executed in order; otherwise, nothing more is done.
One frequently wants to perform one set of statements if some condition is true and some other set of statements otherwise. The optional `else' phrase in an `if' statement allows you to do this:
if (expression)
statements-1
else
statements-2
endif
This statement is executed just like the previous one, except that statements-1 are executed if expression returns a true value and statements-2 are executed otherwise.
Sometimes, one needs to test several conditions in a kind of nested fashion:
if (expression-1)
statements-1
else
if (expression-2)
statements-2
else
if (expression-3)
statements-3
else
statements-4
endif
endif
endif
Such code can easily become tedious to write and difficult to read. MOO provides a somewhat simpler notation for such cases:
if (expression-1)
statements-1
elseif (expression-2)
statements-2
elseif (expression-3)
statements-3
else
statements-4
endif
Note that `elseif' is written as a single word, without any spaces. This simpler version has the very same meaning as the original: evaluate expression-i for i equal to 1, 2, and 3, in turn, until one of them returns a true value; then execute the statements-i associated with that expression. If none of the expression-i return a true value, then execute statements-4.
Any number of `elseif' phrases can appear, each having this form:
elseif (expression) statements
The complete syntax of the `if' statement, therefore, is as follows:
if (expression)
statements
zero-or-more-elseif-phrases
an-optional-else-phrase
endif
Statements for Looping
MOO provides three different kinds of looping statements, allowing you to have a set of statements executed (1) once for each element of a given list, (2) once for each integer or object number in a given range, and (3) over and over until a given condition stops being true.
To perform some statements once for each element of a given list, use this syntax:
for variable in (expression)
statements
endfor
The expression is evaluated and should return a list; if it does not, E_TYPE is raised. The statements are then executed once for each element of that list in turn; each time, the given variable is assigned the value of the element in question. For example, consider the following statements:
odds = {1, 3, 5, 7, 9};
evens = {};
for n in (odds)
evens = {@evens, n + 1};
endfor
The value of the variable `evens' after executing these statements is the list
{2, 4, 6, 8, 10}
To perform a set of statements once for each integer or object number in a given range, use this syntax:
for variable in [expression-1..expression-2]
statements
endfor
The two expressions are evaluated in turn and should either both return integers or both return object numbers; E_TYPE is raised otherwise. The statements are then executed once for each integer (or object number, as appropriate) greater than or equal to the value of expression-1 and less than or equal to the result of expression-2, in increasing order. Each time, the given variable is assigned the integer or object number in question. For example, consider the following statements:
evens = {};
for n in [1..5]
evens = {@evens, 2 * n};
endfor
The value of the variable `evens' after executing these statements is just as in the previous example: the list
{2, 4, 6, 8, 10}
The following loop over object numbers prints out the number and name of every valid object in the database:
for o in [#0..max_object()]
if (valid(o))
notify(player, tostr(o, ": ", o.name));
endif
endfor
The final kind of loop in MOO executes a set of statements repeatedly as long as a given condition remains true:
while (expression)
statements
endwhile
The expression is evaluated and, if it returns a true value, the statements are executed; then, execution of the `while' statement begins all over again with the evaluation of the expression. That is, execution alternates between evaluating the expression and executing the statements until the expression returns a false value. The following example code has precisely the same effect as the loop just shown above:
evens = {};
n = 1;
while (n <= 5)
evens = {@evens, 2 * n};
n = n + 1;
endwhile
Fine point: It is also possible to give a `name' to a `while' loop, using this syntax:
while name (expression)
statements
endwhile
which has precisely the same effect as
while (name = expression)
statements
endwhile
This naming facility is only really useful in conjunction with the `break' and `continue' statements, described in the next section.
With each kind of loop, it is possible that the statements in the body of the loop will never be executed at all. For iteration over lists, this happens when the list returned by the expression is empty. For iteration on integers, it happens when expression-1 returns a larger integer than expression-2. Finally, for the `while' loop, it happens if the expression returns a false value the very first time it is evaluated.