books.o

ds3.0/lib/save/books.o · 601.9 KB

From the archive ds3.0.zip

Download the archive   « Back to the archive contents

#/daemon/books.c
Books (["/doc/manual":(["object":"/domains/default/obj/manual","/doc/manual/chapter39":1164672846,"/doc/manual/chapter38":1164672846,"/doc/manual/chapter37":1164672846,"/doc/manual/chapter36":1164672846,"/doc/manual/chapter35":1164672846,"/doc/manual/chapter34":1164672846,"/doc/manual/chapter33":1164672846,"/doc/manual/chapter32":1164672846,"/doc/manual/chapter31":1164672846,"/doc/manual/chapter30":1164672846,"/doc/manual/chapter19":1164672846,"/doc/manual/chapter18":1164672846,"/doc/manual/chapter17":1164672846,"/doc/manual/chapter16":1164672846,"title":"Untitled","/doc/manual/chapter15":1164672846,"/doc/manual/chapter14":1164672846,"/doc/manual/chapter13":1164672846,"/doc/manual/chapter12":1164672846,"/doc/manual/chapter11":1164672846,"/doc/manual/chapter10":1164672846,"index":"		Untitled

Chapter 1:	\"Introduction to the Coding Environment\"

Chapter 2:	\"The LPC Program\"

Chapter 3:	\"LPC Data Types\"

Chapter 4:	\"Functions\"

Chapter 5:	\"The Basics of Inheritance\"

Chapter 6:	\"Variable Handling\"

Chapter 7:	\"Flow Control\"

Chapter 8:	\"LPC Basics\"

Chapter 9:	\"Introduction to Intermediate LPC\"

Chapter 10:	\"The LPMud Driver\"

Chapter 11:	\"Complex Data Types\"

Chapter 12:	\"The LPC Pre-Compiler\"

Chapter 13:	\"Advanced String Handling\"

Chapter 14:	\"Intermediate Inheritance\"

Chapter 15:	\"Debugging\"

Chapter 16:	\"Armor\"

Chapter 17:	\"Barkeeps\"

Chapter 18:	\"Valid climates\"

Chapter 19:	\"Doors\"

Chapter 20:	\"Items\"

Chapter 21:	\"Meals\"

Chapter 22:	\"NPCs\"

Chapter 23:	\"Properties\"

Chapter 24:	\"Quests\"

Chapter 25:	\"Rooms\"

Chapter 26:	\"Sentients\"

Chapter 27:	\"Towns\"

Chapter 28:	\"Vendors\"

Chapter 29:	\"Weapons\"

Chapter 30:	\"The Natural Language Parser\"

Chapter 31:	\"Overview of the Quick Creation System\"

Chapter 32:	\"QCS: Commands\"

Chapter 33:	\"QCS: Creation\"

Chapter 34:	\"QCS: Modification of NPC's\"

Chapter 35:	\"QCS: Modifying rooms\"

Chapter 36:	\"QCS: Modifying weapons\"

Chapter 37:	\"QCS: Modifying things and stuff\"

Chapter 38:	\"QCS: Adding and deleting\"

Chapter 39:	\"QCS: Final notes\"

Chapter 40:	\"Useful Creator Commands\"

","reads":([({"chapter 34","chapter thirty-four","34",}):"chapter 34 \"QCS: Modification of NPC's\"

    In the previous chapter we learned how to make a generic object.
Now that we have it, what to do with it?

    It's important to keep in mind that the generic thing now in
front of you isn't just a clone from a template file. If the command
you used was \"create npc cowboy\", there is now a file (probably)
called /realms/you/area/npc/cowboy.c that contains the code for the
creature in front of you.
    However, this poor beast has the most uninteresting of features.
It is in fact so boring that it responds only to its generic type.
Such that \"examine cowboy\" or \"kill tex\" won't work. You'll need to
\"look at npc\".

    Accordingly, any modification commands need to be made referring
to the new thing with an it responds to, until such a time as you
change the id to suit your tastes. Let's carry on with the example
of our generic npc. To make a cowboy out of him, we can either
change his name, or his id, or both. Let's start with his name:

%^GREEN%^modify npc name cowboy%^RESET%^

    This makes the SetKeyName() directive in cowboy.c use \"cowboy\"
as its argument, effectively allowing you to address this npc as \"cowboy\"
from now on. Now you can \"look at cowboy\" with some results.
    Obviously our NPC isn't *just* a cowboy. He's also a human, a dude,
and his name is Tex. How do we make him respond to all of these nouns?

%^GREEN%^modify cowboy id%^RESET%^

    You'll notice there are no arguments following the word \"id\". Setting
a thing's id is different from most other settings. If you'll think back
to the LPC datatypes chapter of this manual (you did read the LPC
chapters, didn't you?) you'll remember that some information about 
objects is in the form of strings (\"cowboy\"), some is in the form of
integers (the cowboy's health points, for example) and some is in the
form of arrays, which are a group of data points. In this example we
want the cowboy's id to be an array, because of the many ways we might
want to address him. Therefore, we want the SetId directive in his
file to look like this:

SetId( ({\"human\", \"dude\", \"tex\" }) );

    You might think that QCS should be able to accept multiple values
like this on a line, perhaps with \"modify cowboy id human dude tex\" as
the command. 
    But what if you want this npc to be a \"Boy Named Sue\"? How would
you accommodate id's that contain spaces? In designing QCS, I considered
having escape characters to allow for such things, but ultimately
reasoned that this was just way too much mess. Instead, SetId, and
other directives that take arrays as arguments, are handled by entering
a query session. Below is an example of what it might look like. The
example is necessarily messy because I am including both the queries
and the responses.

---------------------------------------------------
> %^GREEN%^modify npc name cowboy%^RESET%^
Indenting file...
\"/tmp/indent.1136206130.tmp.dat\" 15 lines 420 bytes
Exit from ed.

> %^GREEN%^modify cowboy id%^RESET%^
This setting takes multiple values. If you have no more values to enter, then
enter a dot on a blank line. To cancel, enter a single q on a blank line.
You may now enter the next value. So far, it is blank.
If you're done entering values, enter a dot on a blank line.
%^GREEN%^dude%^RESET%^
You may now enter the next value. So far, we have: ({ \"dude\" })
If you're done entering values, enter a dot on a blank line.
%^GREEN%^human%^RESET%^
You may now enter the next value. So far, we have: ({ \"dude\", \"human\" })
If you're done entering values, enter a dot on a blank line.
%^GREEN%^tex%^RESET%^
You may now enter the next value. So far, we have: ({ \"dude\", \"human\", \"tex\" })
If you're done entering values, enter a dot on a blank line.
%^GREEN%^boy named sue%^RESET%^
You may now enter the next value. So far, we have: ({ \"dude\", \"human\", \"tex\",
\"boy named sue\" })
If you're done entering values, enter a dot on a blank line.
%^GREEN%^.%^RESET%^
Entries complete. Final array is: ({ \"dude\", \"human\", \"tex\", \"boy named sue\" })
Indenting file...
\"/tmp/indent.1136206156.tmp.dat\" 19 lines 459 bytes
Exit from ed.

/open/1136206138: Ok
/realms/cratylus/area/npc/cowboy: Ok
SetId modification complete.
> %^GREEN%^exa tex%^RESET%^
Other than being human, this npc is entirely unremarkable.
The male human is in top condition.
---------------------------------------------------

    If you were now to examine Tex's code (with the command \"about tex\")
you'd see that his SetId directive now looks like this:

SetId( ({\"dude\", \"human\", \"tex\", \"boy named sue\"}) );

    Other NPC features take arrays also. SetAdjectives is one. You
might enter this (mud output omitted for clarity):

%^GREEN%^modify tex adjectives%^RESET%^
%^GREEN%^dusty%^RESET%^
%^GREEN%^hardy%^RESET%^
%^GREEN%^.%^RESET%^
%^GREEN%^look at dusty cowboy%^RESET%^

    There are two other directives that require queries. Things and
NPC's can be looked at, but they can also be smelled and listened
to, if you add SetSmell and SetListen. The syntax is:

%^GREEN%^modify tex smell%^RESET%^

   And you will then be asked a question about keys and mappings.
Understanding mappings is important, but for now you just need to
understand that you are being asked *two* separate questions: 
1) What on the cowboy is being smelled/listened to?
2) What is the smell/sound?

    What this means is that your input will look something like
this:

%^GREEN%^modify tex smell%^RESET%^
%^GREEN%^default%^RESET%^
%^GREEN%^.%^RESET%^
Tex smells of sweat and manure.

    What happens is this:
- You enter the modify command.
- You enter the word \"default\" to indicate this is Tex's general smell.
- You enter a dot to indicate that you are done specifying what
  part of Tex is being smelled.
- You then specify the smell.

    This may seem odd until you realize you can also add smells/listens to
parts of things. Not on NPC's, though. We'll look at this more closely in
later chapters. For now, just use the syntax as shown above. For adding
a listen to the cowboy, it works the same way:

%^GREEN%^modify tex listen%^RESET%^
%^GREEN%^default%^RESET%^
%^GREEN%^.%^RESET%^
Tex seems to be humming a jaunty melody.

    Other features of an NPC do not take arrays, so one-line commands
will do. For example:

%^GREEN%^modify cowboy long This is a cowboy who calls himself Tex, but is in fact a Boy Named Sue.%^RESET%^

%^GREEN%^modify cowboy short a cowboy%^RESET%^

%^GREEN%^modify cowboy level 5%^RESET%^

%^GREEN%^modify cowboy class fighter%^RESET%^

%^GREEN%^modify tex currency gold 1%^RESET%^

%^GREEN%^modify tex currency silver 12%^RESET%^

%^GREEN%^modify tex skill bargaining 5%^RESET%^

%^GREEN%^modify tex skill projectile attack 7%^RESET%^

%^GREEN%^modify tex stat strength 33%^RESET%^

%^GREEN%^modify tex property nice guy 1%^RESET%^

%^GREEN%^modify tex healthpoints 150%^RESET%^

%^GREEN%^modify tex maxhealthpoints 170%^RESET%^

%^GREEN%^modify tex melee 0%^RESET%^

%^GREEN%^modify tex unique 1%^RESET%^

    If you now issue the \"about tex\" command you will see that all
the changes you made have been put into the file.

    You may have noticed the \"melee\" keyword. Dead Souls 2 NPC's come
in various shapes and sizes, and some of them shouldn't wield weapons. A
wolf with a battle axe would be a strange sight indeed. However, the
default combat system makes unarmed creatures extremely vulnerable in
combat.
    To make an NPC combat-capable without weapons, use the new SetMelee
directive. SetMelee(1) makes the NPC capable of proper unarmed combat.
SetMelee(0) makes the NPC a weak opponent if unarmed. 
    NPC's will generally try to bite during unarmed combat. If this
is beneath the capability or dignity of your NPC, you can prevent
this with:

%^GREEN%^modify tex canbite 0%^RESET%^

    If your NPC should try to escape when the battle isn't going
his way, the wimpy settings should do:

%^GREEN%^modify tex wimpy 30%^RESET%^

%^GREEN%^modify tex wimpycommand climb ladder%^RESET%^

    If you don't specify a wimpy command, Tex will leave the 
room through a random exit. In this case, when Tex's health
is down to 30% and he is in combat, he will try to climb a ladder.

    Some NPC's are designed to travel about. To enable this
feature, use the wanderspeed directive:

%^GREEN%^modify tex wanderspeed 5%^RESET%^

    If you want him to travel more quickly, use a
lower number. By default, wandering NPC's only wander in rooms
that have already been loaded into memory. They avoid loading
rooms because loading a bunch of rooms that only the NPC
will ever see is a waste of your mud's resources.
    However, if you *do* want your NPC to wander in an
unrestricted manner, regardless of whether a room is loaded,
use the permitload directive:

%^GREEN%^modify tex permitload 1%^RESET%^

    By default, NPC's stand up when they can. This is
so that if they collapse during combat, they try to
get back up once they are able to do so.
    If you prefer that your NPC maintain some other
posture, you can set that posture, then disable
autostanding like this:

%^GREEN%^modify tex posture lying%^RESET%^

%^GREEN%^modify tex autostand 0%^RESET%^

    If he's especially lazy, you can have him take
a nap this way:

%^GREEN%^modify tex sleeping 10%^RESET%^

    Which will have him wake up after about a minute.
However, note that if you've disabled autostanding,
he will remain lying down after he wakes up.

    If the NPC should be hostile, that is, he should
attack any creatures that it sees enter a room, 
SetEncounter should do it:

%^GREEN%^modify tex encounter 100%^RESET%^

    This means that if the creature it sees has a
charisma score of less than 100 (which should pretty
much be always true), Tex will try to kill it. You
can do some fancy stuff with SetEncounter, such
as only attacking orcs, or actually doing something
friendly, but to do so you can't use QCS. Read
the NPC and Sentients chapter in the Creator's
Manual for details on how to code such stuff.

    If the NPC is a golem or other such non-biological
creature, it may be useful to specify what they are
made of. The SetComposition setting for a clay
golem might look like this:

%^GREEN%^modify golem composition clay%^RESET%^

    If it happens to be a golem that does not believe
in violence as a solution to problems, you can 
make refuse to hurt others with the following:

%^GREEN%^modify golem pacifist 1%^RESET%^


Vendors:
-------

Vendors are a special kind of NPC that can sell stuff.
Along with the standard NPC settings, vendors have
the following:

SetStorageRoom specifies where the vendor's stock
is stored. If a valid room is specified, anything
in that room can be sold by the vendor.

SetLocalCurrency specifies the type of currency,
such as gold or silver, that the vendor accepts.

SetMaxItems is the maximum number of items in
the storeroom that the vendor is permitted to sell.

SetVendorType specifies the kind of stuff the vendor can
trade in. \"all\" allows him to buy and sell whatever.
But if he is a weapon vendor, he can't trade in armor,
etc. See /include/vendor_types.h for the available
vendor types. To have a \"multi-type\" vendor, you'll have to
code it by hand. The result of that looks something
like this:

SetVendorType( VT_TREASURE | VT_ARMOR | VT_HERBS );


Barkeeps:
--------

    Like vendors, barkeeps sell stuff, but they are
limited to selling food and drink.

    Unlike vendors, barkeeps have no limitation on
the amount of stuff they can sell. They also do
not have a storeroom. The stuff they can sell is
specified in their SetMenu directive, like this:

%^GREEN%^clone woody%^RESET%^
You clone a generic barkeep (/realms/temujin/area/npc/woody.c).
%^GREEN%^modify woody menu%^RESET%^
If you don't understand these questions, type the letter q on a blank line and hit enter.

Please enter the first key element for this mapping:

%^GREEN%^bourbon%^RESET%^
Please enter the next key element, or enter a single dot to finish entering key elements.
%^GREEN%^whiskey%^RESET%^
Please enter the next key element, or enter a single dot to finish entering key elements.
%^GREEN%^.%^RESET%^
Please enter the value for key ({ \"bourbon\", \"whiskey\" }):

%^GREEN%^/domains/town/meals/bourbon%^RESET%^

    Barkeeps also have the SetLocalCurrency directive
to specify the currency they accept.


",({"chapter 13","chapter thirteen","13",}):"chapter 13 \"Advanced String Handling\"
Intermediate LPC
Descartes of Borg
November 1993

                     Chapter 5: Advanced String Handling

5.1 What a String Is
The LPC Basics textbook taught strings as simple data types.  LPC
generally deals with strings in such a matter.  The underlying driver
program, however, is written in C, which has no string data type.  The
driver in fact sees strings as a complex data type made up of an array of
characters, a simple C data type.  LPC, on the other hand does not
recognize a character data type (there may actually be a driver or two out
there which do recognize the character as a data type, but in general not). 
The net effect is that there are some array-like things you can do with
strings that you cannot do with other LPC data types.

The first efun regarding strings you should learn is the strlen() efun. 
This efun returns the length in characters of an LPC string, and is thus
the string equivalent to sizeof() for arrays.  Just from the behaviour of
this efun, you can see that the driver treats a string as if it were made up
of smaller elements.  In this chapter, you will learn how to deal with
strings on a more basic level, as characters and sub strings.

5.2 Strings as Character Arrays
You can do nearly anything with strings that you can do with arrays,
except assign values on a character basis.  At the most basic, you can
actually refer to character constants by enclosing them in '' (single
quotes).  'a' and \"a\" are therefore very different things in LPC.  'a'
represents a character which cannot be used in assignment statements or
any other operations except comparison evaluations.  \"a\" on the other
hand is a string made up of a single character.  You can add and subtract
other strings to it and assign it as a value to a variable.

With string variables, you can access the individual characters to run
comparisons against character constants using exactly the same syntax
that is used with arrays.  In other words, the statement:
    if(str[2] == 'a')
is a valid LPC statement comparing the second character in the str string
to the character 'a'.  You have to be very careful that you are not
comparing elements of arrays to characters, nor are you comparing
characters of strings to strings.

LPC also allows you to access several characters together using LPC's
range operator ..:
    if(str[0..1] == \"ab\")
In other words, you can look for the string which is formed by the
characters 0 through 1 in the string str.  As with arrays, you must be
careful when using indexing or range operators so that you do not try to
reference an index number larger than the last index.  Doing so will
result in an error.

Now you can see a couple of similarities between strings and arrays:
1) You may index on both to access the values of individual elements.
	a) The individual elements of strings are characters
	b) The individual elements of arrays match the data type of the
array.
2) You may operate on a range of values
	a) Ex: \"abcdef\"[1..3] is the string \"bcd\"
	b) Ex: ({ 1, 2, 3, 4, 5 })[1..3] is the int array ({ 2, 3, 4 })

And of course, you should always keep in mind the fundamental
difference: a string is not made up of a more fundamental LPC data type. 
In other words, you may not act on the individual characters by
assigning them values.

5.3 The Efun sscanf()
You cannot do any decent string handling in LPC without using
sscanf().  Without it, you are left trying to play with the full strings
passed by command statements to the command functions.  In other
words, you could not handle a command like: \"give sword to leo\", since
you would have no way of separating \"sword to leo\" into its constituent
parts.  Commands such as these therefore use this efun in order to use
commands with multiple arguments or to make commands more
\"English-like\".

Most people find the manual entries for sscanf() to be rather difficult
reading.  The function does not lend itself well to the format used by
manual entries.  As I said above, the function is used to take a string and
break it into usable parts.  Technically it is supposed to take a string and
scan it into one or more variables of varying types.  Take the example
above:

int give(string str) {
    string what, whom;

    if(!str) return notify_fail(\"Give what to whom?\\n\");
    if(sscanf(str, \"%s to %s\", what, whom) != 2) 
      return notify_fail(\"Give what to whom?\\n\");
    ... rest of give code ...
}

The efun sscanf() takes three or more arguments.  The first argument is
the string you want scanned.  The second argument is called a control
string.  The control string is a model which demonstrates in what form
the original string is written, and how it should be divided up.  The rest
of the arguments are variables to which you will assign values based
upon the control string.

The control string is made up of three different types of elements: 1)
constants, 2) variable arguments to be scanned, and 3) variable
arguments to be discarded.  You must have as many of the variable
arguments in sscanf() as you have elements of type 2 in your control
string.  In the above example, the control string was \"%s to %s\", which
is a three element control string made up of one constant part (\" to \"),
and two variable arguments to be scanned (\"%s\").  There were no
variables to be discarded.

The control string basically indicates that the function should find the
string \" to \" in the string str.  Whatever comes before that constant will
be placed into the first variable argument as a string.  The same thing
will happen to whatever comes after the constant.

Variable elements are noted by a \"%\" sign followed by a code for
decoding them.  If the variable element is to be discarded, the \"%\" sign
is followed by the \"*\" as well as the code for decoding the variable. 
Common codes for variable element decoding are \"s\" for strings and \"d\"
for integers.  In addition, your mudlib may support other conversion
codes, such as \"f\" for float.  So in the two examples above, the \"%s\" in
the control string indicates that whatever lies in the original string in the
corresponding place will be scanned into a new variable as a string.

A simple exercise.  How would you turn the string \"145\" into an
integer?

Answer:
int x;
sscanf(\"145\", \"%d\", x);

After the sscanf() function, x will equal the integer 145.

Whenever you scan a string against a control string, the function
searches the original string for the first instance of the first constant in
the original string.  For example, if your string is \"magic attack 100\" and
you have the following:
int improve(string str) {
    string skill;
    int x;

    if(sscanf(str, \"%s %d\", skill, x) != 2) return 0;
    ...
}
you would find that you have come up with the wrong return value for
sscanf() (more on the return values later).  The control string, \"%s %d\",
is made up of to variables to be scanned and one constant.  The constant
is \" \".  So the function searches the original string for the first instance
of \" \", placing whatever comes before the \" \" into skill, and trying to
place whatever comes after the \" \" into x.  This separates \"magic attack
100\" into the components \"magic\" and \"attack 100\".  The function,
however, cannot make heads or tales of \"attack 100\" as an integer, so it
returns 1, meaning that 1 variable value was successfully scanned
(\"magic\" into skill).

Perhaps you guessed from the above examples, but the efun sscanf()
returns an int, which is the number of variables into which values from
the original string were successfully scanned.  Some examples with
return values for you to examine:

sscanf(\"swo  rd descartes\", \"%s to %s\", str1, str2)           return: 0
sscanf(\"swo  rd descartes\", \"%s %s\", str1, str2)              return: 2
sscanf(\"200 gold to descartes\", \"%d %s to %s\", x, str1, str2) return: 3
sscanf(\"200 gold to descartes\", \"%d %*s to %s\", x, str1)      return: 2
where x is an int and str1 and str2 are string

5.4 Summary
LPC strings can be thought of as arrays of characters, yet always
keeping in mind that LPC does not have the character data type (with
most, but not all drivers).  Since the character is not a true LPC data
type, you cannot act upon individual characters in an LPC string in the
same manner you would act upon different data types.  Noticing the
intimate relationship between strings and arrays nevertheless makes it
easier to understand such concepts as the range operator and indexing on
strings.

There are efuns other than sscanf() which involve advanced string
handling, however, they are not needed nearly as often.  You should
check on your mud for man or help files on the efuns: explode(),
implode(), replace_string(), sprintf().  All of these are very valuable
tools, especially if you intend to do coding at the mudlib level.

Copyright (c) George Reese 1993
",({"chapter 15","chapter fifteen","15",}):"chapter 15 \"Debugging\"
Intermediate LPC
Descartes of Borg
November 1993

                            Chapter 7: Debugging

7.1 Types of Errors
By now, you have likely run into errors here, there, and everywhere.  In
general, there are three sorts of errors you might see: compile time
errors, run time errors, and malfunctioning code.  On most muds you
will find a personal file where your compile time errors are logged.  For
the most part, this file can be found either in your home directory as the
file named \"log\" or \".log\", or somewhere in the directory \"/log\" as a file
with your name..  In addition, muds tend to keep a log of run time errors
which occur while the mud is up.  Again, this is generally found in
\"/log\".  On MudOS muds it is called \"debug.log\".  On other muds it may
be called something different like \"lpmud.log\".  Ask your administrators
where compile time and run time errors are each logged if you do not
already know.

Compile time errors are errors which occur when the driver tries to load
an object into memory.  If, when the driver is trying to load an object
into memory, it encounters things which it simply does not understand
with respect to what you wrote, it will fail to load it into memory and log
why it could not load the object into your personal error log.  The most
common compile time errors are typos, missing or extra (), {}. [], or \"\",
and failure to declare properly functions and variables used by the
object.

Run time errors occur when something wrong happens to an object in
memory while it is executing a statement.  For example, the driver
cannot tell whether the statement \"x/y\" will be valid in all circumstances. 
In fact, it is a valid LPC expression.  Yet, if the value of y is 0, then a
run time error will occur since you cannot divide by 0.  When the driver
runs across an error during the execution of a function, it aborts
execution of the function and logs an error to the game's run time error
log.  It will also show the error to this_player(), if defined, if the player
is a creator, or it will show \"What?\" to players.  Most common causes
for run time errors are bad values and trying to perform operations with
data types for which those operations are not defined.

The most insideous type of error, however, is plain malfunctioning
code.  These errors do not log, since the driver never really realizes that
anything is wrong.  In short, this error happens when you think the code
says one thing, but in fact it says another thing.  People too often
encounter this bug and automatically insist that it must be a mudlib or
driver bug.  Everyone makes all types of errors though, and more often
than not when code is not functioning the way you should, it will be
because you misread it.  

7.2 Debugging Compile Time Errors
Compile time errors are certainly the most common and simplest bugs to
debug.  New coders often get frustrated by them due to the obscure
nature of some error messages.  Nevertheless, once a person becomes
used to the error messages generated by their driver, debugging compile
time errors becomes utterly routine.

In your error log, the driver will tell you the type of error and on which
line it finally noticed there was an error.  Note that this is not on which
line the actual error necessarily exists.  The most common compile time
error, besides the typo, is the missing or superfluous parentheses,
brackets, braces, or quotes.  Yet this error is the one that most baffles
new coders, since the driver will not notice the missing or extra piece
until well after the original.  Take for example the following code:

1 int test(string str) {
2    int x;
3    for(x =0; x<10; x++)
4        write(x+\"\\n\");
5    }
6    write(\"Done.\\n\");
7 }

Depending on what you intended, the actual error here is either at line 3
(meaning you are missing a {) or at line 5 (meaing you have an extra }). 
Nevertheless, the driver will report that it found an error when it gets to
line 6.  The actual driver message may vary from driver to driver, but no
matter which driver, you will see an error on line 6, since the } in line 5
is interpreted as ending the function test().  At line 6, the driver sees that
you have a write() sitting outside any function definition, and thus
reports an error.  Generally, the driver will also go on to report that it
found an error at line 7 in the form of an extra }.

The secret to debugging these is coding style.  Having closing } match
up vertically with the clauses they close out helps you see where you are
missing them when you are debugging code.  Similarly, when using
multiple sets of parentheses, space out different groups like this:
    if( (x=sizeof(who=users()) > ( (y+z)/(a-b) + (-(random(7))) ) ) 
As you can see, the parentheses for the for() statement, are spaced out
from the rest of the statement.  In addition, individual sub-groups are
spaced so they can easily be sorted out in the event of an error.

Once you have a coding style which aids in picking these out, you learn
which error messages tend to indicate this sort of error.  When
debugging this sort of error, you then view a section of code before and
after the line in question.  In most all cases, you will catch the bug right
off.

Another common compile time error is where the driver reports an
unknown identifier.  Generally, typos and failure to declare variables
causes this sort of error.  Fortunately, the error log will almost always
tell you exactly where the error is.  So when debugging it, enter the
editor and find the line in question.  If the problem is with a variable and
is not a typo, make sure you declared it properly.  On the other hand, if
it is a typo, simply fix it!

One thing to beware of, however, is that this error will sometimes be
reported in conjunction with a missing parentheses, brackets, or braces
type error.  In these situations, your problem with an unknown identifier
is often bogus.  The driver misreads the way the {} or whatever are
setup, and thus gets variable declarations confused.  Therefore make
sure all other compile time errors are corrected before bothering with
these types of errors.

In the same class with the above error, is the general syntax error.  The
driver generates this error when it simply fails to understand what you
said.  Again, this is often caused by typos, but can also be caused by not
properly understanding the syntax of a certain feature like writing a for()
statement: for(x=0, x<10, x++).  If you get an error like this which is
not a syntax error, try reviewing the syntax of the statement in which the
error is occurring.

7.3 Debugging Run Time Errors
Run time errors are much more complex than their compile time
counterparts.  Fortunately these errors do get logged, though many
creators do not realise or they do not know where to look.  The error log
for run time errors are also generally much more detailed than compile
time errors, meaning that you can trace the history of the execution train
from where it started to where it went wrong.  You therefore can setup
debugging traps using precompiler statements much easier using these
logs.  Run time errors, however, tend to result from using more
complex codign techniques than beginners tend to use, which means you
are left with errors which are generally more complicated than simple
compile time errors.

Run time errors almost always result from misusing LPC data types. 
Most commonly, trying to do call others using object variables which are
NULL, indexing on mapping, array, or string variables which are
NULL, or passing bad arguments to functions.  We will look at a real
run time error log from Nightmare:

Bad argument 1 to explode()
program: bin/system/_grep.c, object: bin/system/_grep
line 32
'       cmd_hook' in '        std/living.c' ('      
std/user#4002')line 83
'       cmd_grep' in '  bin/system/_grep.c' ('   
bin/system/_grep')line 32     
Bad argument 2 to message()
program: adm/obj/simul_efun.c, object: adm/obj/simul_efun
line 34
'       cmd_hook' in '        std/living.c' ('      
std/user#4957')line 83
'       cmd_look' in '  bin/mortal/_look.c' ('   
bin/mortal/_look')line 23
' examine_object' in '  bin/mortal/_look.c' ('   
bin/mortal/_look')line 78
'          write' in 'adm/obj/simul_efun.c' (' 
adm/obj/simul_efun')line 34
Bad argument 1 to call_other()
program: bin/system/_clone.c, object: bin/system/_clone
line 25
'       cmd_hook' in '        std/living.c' ('      
std/user#3734')line 83
'      cmd_clone' in ' bin/system/_clone.c' ('  
bin/system/_clone')line 25
Illegal index
program: std/monster.c, object:
wizards/zaknaifen/spy#7205 line 76
'     heart_beat' in '       std/monster.c'
('wizards/zaknaifen/spy#7205')line
76                                                                                  

All of the errors, except the last one, involve passing a bad argument to a
function.  The first bug, involves passing a bad first arument to the efun
explode().  This efun expects a string as its first argment.  In debugging
these kinds of errors, we would therefore go to line 32 in
/bin/system/_grep.c and check to see what the data type of the first
argument being passed in fact is.  In this particular case, the value being
passed should be a string.

If for some reason I has actually passed something else, I would be done
debugging at that point and fix it simply by making sure that I was
passing a string.  This situation is more complex.  I now need to trace
the actual values contained by the variable being passed to explode, so
that I can see what it is the explode() efun sees that it is being passed.

The line is question is this:
 borg[files[i]] = regexp(explode(read_file(files[i]), \"\\n\"), exp);
where files is an array for strings, i is an integer, and borg is a mapping. 
So clearly we need to find out what the value of read_file(files[i]) is. 
Well, this efun returns a string unless the file in question does not exist,
the object in question does not have read access to the file in question, or
the file in question is an empty file, in which cases the function will
return NULL.  Clearly, our problem is that one of these events must
have happened.  In order to see which, we need to look at files[i].

Examining the code, the files array gets its value through the get_dir()
efun.  This returns all the files in a directory if the object has read access
to the directory.  Therefore the problem is neither lack of access or non-
existent files.  The file which caused this error then must have been an
empty file.  And, in fact, that is exactly what caused this error.  To
debug that, we would pass files through the filter() efun and make
sure that only files with a file size greater than 0 were allowed into the
array.

The key to debugging a run time error is therefore knowing exactly what
the values of all variables in question are at the exact moment where the
bug created.  When reading your run time log, be careful to separate the
object from the file in which the bug occurred.  For example, the
indexing error above came about in the object /wizards/zaknaifen/spy,
but the error occured while running a function in /std/monster.c, which
the object inherited.

7.4 Malfunctioning Code
The nastiest problem to deal with is when your code does not behave the
way you intended it to behave.  The object loads fine, and it produces no
run time errors, but things simply do not happen the way they should. 
Since the driver does not see a problem with this type of code, no logs
are produced.  You therefore need to go through the code line by line
and figure out what is happening.

Step 1: Locate the last line of code you knew successfully executed
Step 2: Locate the first line of code where you know things are going
wrong
Step 3: Examine the flow of the code from the known successful point to
the first known unsuccessful point.

More often than not, these problems occurr when you are using if()
statements and not accounting for all possibilities.  For example:

int cmd(string tmp) {
    if(stringp(tmp)) return do_a()
    else if(intp(tmp)) return do_b()
    return 1;
}

In this code, we find that it compiles and runs fine.  Problem is nothing
happens when it is executed.  We know for sure that the cmd() function
is getting executed, so we can start there.  We also know that a value of
1 is in fact being returned, since we do not see \"What?\" when we enter
the command.  Immediately, we can see that for some reason the
variable tmp has a value other than string or int.  As it turns out, we
issued the command without parameters, so tmp was NULL and failed
all tests.

The above example is rather simplistic, bordering on silly. 
Nevertheless, it gives you an idea of how to examine the flow of the
code when debugging malfunctioning code.  Other tools are available as
well to help in debugging code.  The most important tool is the use of
the precompiler to debug code.  With the code above, we have a clause
checking for integers being passed to cmd().  When we type \"cmd 10\",
we are expecting do_b() to execute.  We need to see what the value of
tmp is before we get into the loop:

#define DEBUG
int cmd(string tmp) {
#ifdef DEBUG
    write(tmp);
#endif
    if(stringp(tmp)) return do_a();
    else if(intp(tmp)) return do_b();
    else return 1;
}

We find out immediately upon issuing the command, that tmp has a
value of \"10\".  Looking back at the code, we slap ourselves silly,
forgetting that we have to change command arguments to integers using
sscanf() before evaluating them as integers.

7.5 Summary
The key to debugging any LPC problem is always being aware of what
the values of your variables are at any given step in your code.  LPC
execution reduces on the simplest level to changes in variable values, so
bad values are what causes bad things to happen once code has been
loaded into memory.  If you get errors about bad arguments to
functions, more likely than not you are passing a NULL value to a
function for that argument.  This happens most often with objects, since
people will do one of the following:
    1) use a value that was set to an object that has since destructed
    2) use the return value of this_player() when there is no this_player()
    3) use the return value of this_object() just after this_object() was
    destructed

In addition, people will often run into errors involving illegal indexing or
indexing on illegal types.  Most often, this is because the mapping or
array in question was not initialized, and therefore cannot be indexed. 
The key is to know exactly what the full value of the array or mapping
should be at the point in question.  In addition, watch for using index
numbers larger than the size of given arrays

Finally, make use of the precompiler to temporarly throw out code, or
introduce code which will show you the values of variables.  The
precompiler makes it easy to get rid of debugging code quickly once you
are done.  You can simply remove the DEBUG define when you are
done.

Copyright (c) George Reese 1993
",({"chapter 29","chapter twenty-nine","29",}):"chapter 29 \"Weapons\"
			   Building Weapons
		     The Nightmare IV LPC Library
		 written by Descartes of Borg 950429

All items in the Nightmare LPC Library (descendants of /lib/item.c)
are weapons.  A player can, for example, use a can of spam as a
weapon.  However, they are set up as extremely pathetic weapons.  This
document describes in detail how to make an object into a real weapon.

I. Basic Stuff
The basic weapon is exactly the same as the basic item.  You can do
anything to it that can be done to other items.  For details on items,
see /doc/build/Items.  The simple weapon should look like this:

#include <lib.h>
#include <damage_types.h>
#include <vendor_types.h>

inherit LIB_ITEM;

static void create() {
    item::create();
    SetKeyName(\"short sword\");
    SetId( ({ \"sword\", \"short sword\", \"a short sword\" }) );
    SetAdjectives( ({ \"short\" }) );
    SetShort(\"a short sword\");
    SetLong(\"A rusty short sword with specs of blood on it.\");
    SetVendorType(VT_WEAPON);
    SetDamagePoints(1500);
    SetClass(12);
    SetValue(150);
    SetMass(100);
    SetWeaponType(\"blade\");
    SetDamageType(BLADE);
}

The last part is what differs from regular items.  Note the functions:

SetVendorType()
SetClass()
SetWeaponType()
SetDamageType()

The available vendor types can be found by reading the file
/include/vendor_types.h.  Similarly, damage types may be found by
reading /include/damage_types.h.  The vendor type states what sort of
stores can carry this item.  VT_WEAPON should almost ALWAYS be the
vendor type you give for weapons.

SetClass()
The class is the basic weapon strength.  It is how much damage gets
done without any modification.  This number ranges between 1 and 100,
where 1 is a pathetic weapon (the class for basic items) and 100 is
probably bordering on illegal.

SetWeaponType()
This sets what sort of attack skill the player needs to use this
weapon.  The weapon types are:
blade
knife
blunt
projectile

SetDamageType()
Damage types, again, are found in /include/damage_types.h.  This sets
what type of damage is done by this weapon to its victims.

II. Wield Functions

mixed SetWield(string | function) 
Examples:
	SetWield(\"The short sword feels dull as you wield it.\");
	SetWield( (: WieldMe :) );

If you pass a string to SetWield(), then the player sees that string
whenever they wield the weapon.  If, on the other hand, you pass a
function, then that function will get called just before the weapon is
wielded when the player issues the wield command.  The function you
pass should be written in the form of:

int WieldMe();

If the function returns 1, then the player can wield the weapon.  If
it returns 0, then the player cannot wield the weapon.  Note that if
you have a wield function, you are responsible for all messaging to
the player to let the player know that they can/cannot wield the
weapon.  Example:

int WieldMe() {
    if( (int)this_player()->ClassMember(\"fighter\") ) {
        write(\"The short sword gives you power as you wield it.\");
        say((string)this_player()->GetName() + \" wields a short sword.\");
        return 1;
    }
    else {
        write(\"You are not worthy of this short sword.\");
        return 0;
    }
}


III. Modifying Stats and Skills
A common thing people like to do with weapons is temporarily modify a
player's skills.  This is done by making use of the function
AddStatBonus() and AddSkillBonus().  Most of the time this is done
through a SetWield() function.

void AddStatBonus(string stat, function f);
void AddSkillBonus(string stat, function f);

Examples:
	this_player()->AddStatBonus(\"wisdom\", (: CheckStat :));
	this_player()->AddSkillBonus(\"blade attack\", (: CheckSkill :));

The functions then have the format:

int CheckWhatever(string stat_or_skill);

NOTE: You should always check whether the bonus is still in effect.
For example, make sure the weapon is still wielded if it results from
wielding the weapon.  For example:

#include <lib.h>

inherit LIB_ITEM;

int DoWield()
int CheckBlade(string skill);

static void create() {
...
    SetWield((: DoWield :));
...
}

int DoWield() { 
    this_player()->AddSkillBonus(\"blade attack\", (: CheckBlade :) );
    write(\"You wield the short sword.\");
    say((string)this_player()->GetName() + \" wields a short sword.\");
    return 1;
}

int CheckBlade(string skill) {
    if( !GetWorn() ) {
        previous_object()->RemoveSkillBonus(\"blade\", this_object());
        return 0;
    }
    else return 5;
}


In other words, this weapon will give its wielder a blade attack bonus
of 5.  Note that you must use previous_object() in CheckBlade() and
NOT this_player() because there is no way of knowing who this_player()
is at the time.  You do know, however, that the object calling
CheckBlade() is always the player for whom the skill bonus is made.
Always remember to remove bonuses.

IV. Modifying Hits
The Nightmare IV LPC Library uses an event driven combat system.  With
respect to weapons, a round of combat is broken down into the
following events:

1. The person wielding the weapon uses it.
2. If they cannot hit a motionless target, the round ends.
3. If the target dodges the attack, the round ends.
4. eventStrike() is called in the weapon to determine how much damage
the weapon can do.
5. eventReceiveDamage() is called in the target object.  This in turn:
	a. Calls eventReceiveDamage() in all armour objects, which each:
		i. Calls eventReceiveDamage() in the weapon
		ii. The weapon wears down a bit
	b. The armour wears down a bit
	c. The amount of armour damage absorbed is returned
	d. The target objects loses health points.
	f. The amount of damage done is returned.
6. Skill and stat points are added.

Note the two important functions which get called in weapon.c:

	int eventStrike(object ob);
	int eventReceiveDamage(int type, int amount, int unused, mixed limbs);

By default, eventStrike() returns the value of GetClass().  However,
you can modify this value by overriding the eventStrike().  For
example:

int eventStrike(object target) {
    if( (string)target->GetRace() != \"orc\" ) return item::eventStrike(target);
    message(\"environment\", \"The orc slayer makes a nasty sound!\",
      environment(target));
    return item::eventStrike(target) + random(10);
}

NOTE: You should always use item::eventStrike() rather than hard coded
values since weapon class deteriorates over time.

In this example, a random(10) points of extra damage gets done to
orcs.  This would be the orc slayer weapon of ancient fame.

For those familiar with hit functions in the old Nightmare Mudlibs,
this would be roughly equivalent to that.

Another place where you can make things happen is in
eventDeteriorate() which gets called by eventReceieveDamage().  This is
where a weapon wears down from the shock which armour has absorbed
from it.  For weapons, there is not much which can be done here, but
this document points it out for the creative who feel they might be able to do
somthing with it.

	Descartes of Borg
	borg@imaginary.com
",({"chapter 17","chapter seventeen","17",}):"chapter 17 \"Barkeeps\"
		   Building Food and Drink Sellers
		     The Nightmare IV LPC Library
		 written by Descartes of Borg 950528

This document details the building of barkeeps, waiters, and other
such people who sell food and drink.  Barkeeps are NPC's, and
therefore everythign which applies to NPC's applies to barkeeps.  

To build a barkeep, you should inherit LIB_BARKEEP.

Beyond the functions specific to NPC's barkeeps also make use of the
following functions:

mapping SetMenuItems(mapping menu);
mapping AddMenuItem(string item, string file);
mapping RemoveMenuItem(string item);
mapping GetMenuItems();
string SetLocalCurrency(string curr);

When building a barkeep, you must add some mechanism in the room in
which the barkeep is placed for people to view a list of things for
sale.

*****
mapping SetMenuItems(mapping menu);
*****

Example: SetMenuItems( ([ \"coffee\" : \"/realms/descartes/coffee\" ]) );

Sets which menu items are found in which file.  This is a mapping with
the name of the item as a key and the file in which it is located as
the value.

*****
mapping AddMenuItem(string item, string file);
*****

Example: AddMenuItem(\"lobster\", \"/realms/descartes/lobster\");

Adds one menu item at a time to the list of menu items.

*****
mapping RemoveMenuItem(string item);
*****

Example: RemoveMenuItem(\"coffee\");

Removes the named item from the menu.

*****
mapping GetMenuItems();
*****

Returns all the menu items for this barkeep.  Useful in building your
menu list.

*****
string SetLocalCurrency(string curr);
*****

Example: SetLocalCurrency(\"khucha\");

Sets the currency in which the barkeep does business.




",({"chapter 37","chapter thirty-seven","37",}):"chapter 37 \"QCS: Modifying things and stuff\"

    You should have a firm grasp now on how QCS works
in relation to manipulable objects. Let's look at the
settings for a few special kinds of items:

chairs
------

%^GREEN%^modify stool maxsitters 1%^RESET%^

%^GREEN%^modify stool setmaxcarry 200%^RESET%^


beds
----

%^GREEN%^modify sofa maxsitters 2%^RESET%^

%^GREEN%^modify sofa maxliers 1%^RESET%^

%^GREEN%^modify sofa maxcarry 400%^RESET%^


containers 
----------

%^GREEN%^modify box canclose 1%^RESET%^

%^GREEN%^modify box closed 1%^RESET%^

%^GREEN%^modify box locked 1%^RESET%^

%^GREEN%^modify box key magic_skeleton_key%^RESET%^

%^GREEN%^modify box maxcarry 200%^RESET%^

%^GREEN%^modify box setmoney gold 15%^RESET%^


tables
------

%^GREEN%^modify altar maxcarry 300%^RESET%^

%^GREEN%^modify altar maxliers 1%^RESET%^


meals/drinks
------------

%^GREEN%^modify burger mealtype food%^RESET%^

%^GREEN%^modify schlitz mealtype alcohol%^RESET%^

%^GREEN%^modify apple mealstrength 10%^RESET%^


books
-----

%^GREEN%^modify journal title The Orc Within%^RESET%^

%^GREEN%^modify journal source /domains/Orcland/etc/books/journal%^RESET%^


Readable things:
----------------

If you want to be able to \"read thing\", for example, \"read sign\":

%^GREEN%^modify sign defaultread This is a message written on the sign.%^RESET%^

If you want to make a thing on a thing readable, as in
\"read inscription on ring\":

%^GREEN%^modify ring item%^RESET%^

%^GREEN%^inscription%^RESET%^

%^GREEN%^.%^RESET%^

%^GREEN%^This is an inscription on the ring. Try 'read inscription on ring'%^RESET%^

%^GREEN%^modify ring read%^RESET%^

%^GREEN%^inscription%^RESET%^

%^GREEN%^.%^RESET%^

%^GREEN%^So! We, the spear-Danes%^RESET%^

By default, readabale items are readable by anyone, regardless
of the languages they know. If, however, your item should
only be readable by someone who understands the elvish tongue:

%^GREEN%^modify ring language edhellen%^RESET%^


Miscellaneous:
--------------

To make a key have a 50% chance of breaking when it's used:

%^GREEN%^modify golden key disablechance 50%^RESET%^


To make a room or object immune to resets:

%^GREEN%^modify sentry noclean 1%^RESET%^


To make sure there is only one instance of an object or
NPC loaded at any given time:

%^GREEN%^modify tiamat unique 1%^RESET%^


To make a thing or room immune to the QCS (except for this
command):

%^GREEN%^modify workroom nomodify 1%^RESET%^


To specify what kind of vendor should be allowed to traffic
in this item:

%^GREEN%^modify necklace vendortype treasure%^RESET%^


",({"chapter 33","chapter thirty-three","33",}):"chapter 33 \"QCS: Creation\"

    Creation breaks down into three categories. \"Things\", rooms, and
doors. Let's look at things first:

Thing creation:
---------------
    In this category we're including NPC's, weapon, armor, unspecial items,
tables, furniture, books and containers. Basically things that actually show
up somewhere. A door is a very special sort of object and does not fall
under this category.

    To make a new thing, the syntax looks like this:

create THING FILENAME

    The THING is the category of item we are creating. The FILENAME is
the name of the file that will contain this item's configuration data.
You may enter an absolute path, or you may simply enter a filename. If
you enter a filename, QCS will attempt to figure out the best place
for this file. If your current working directory has a name QCS understands
as being compatible with the type of object you are making (for example,
your cwd is /realms/you/npc and you are making an NPC) it will use that.
Otherwise it will search parent and children directories for a 
directory name it understands this way. Finally, if it can find no
compatible directories for your file near your cwd, it will put it in
the appropriate directory in your home area (in this case, 
/realms/you/area/npc ).
    Avoid a relative path. It probably won't work the way you think.

   When the command completes, FILENAME will be a file containing the
data for your generic thing, and a copy of that generic thing will appear
in the room you are in.
    If, for example, you entered:

%^GREEN%^create npc cowboy%^RESET%^

    The room you are in will contain a generic NPC which *does not* 
answer to the id of \"cowboy\". This NPC is just a generic NPC whose
filename is (probably) /realms/you/npc/cowboy.c and isn't yet a real
cowboy. You'll need to use the \"modify\" command to make a proper
cowboy out of him.


Room creation
-------------

    Naturally, if you create a room, a new room will not appear inside
your current environment. Instead, the syntax of the \"create\" command
is different when you want to create a new room.

    You may have noticed that you can't use the \"create\" command to make
a new room adjacent to your workroom. This is for your protection and
my sanity. Files which contain the directive \"SetNoModify(1)\" are
immune to QCS manipulation. 
    Rooms like your workroom, the default start room, the void room, etc,
are set nomodify. This is because if you screw it up, you will be
sorry, and I just don't want to hear it.
    So, suppose then that you're in your sample room (one room east 
of your workroom) and you want to make a new room. You might issue
the following command:

%^GREEN%^create room south testroom1%^RESET%^

    What this does is copy the room you are in (in this case,
/realms/you/area/sample_room.c) to a new location (perhaps
/realms/you/area/testroom1.c). But the neat thing is, this new room
does not have the same exits as the room you are in. The new room
has just one exit, leading back to where you are.
    The net effect of all this is that when you issue this command, 
you make a new room in the direction you specify, and this
new room looks just like the room you're in, only the exits are such
that you can travel back and forth between the rooms. 

    
Door creation
-------------

    Doors are funny things. In Dead Souls, they aren't objects in the 
conventional sense of a thing which occupies a room you're in. Rather,
they are really daemons which attach to adjoining rooms. If that doesn't
make sense to you, don't worry. You're not alone.

    The syntax for door creation is much like that for room creation.
After you create that room south of your sample room, you can now create
a door between them:

%^GREEN%^create door south sample_door%^RESET%^

    This brings into existence a generic door (closed by default) which
is between the two rooms.


",({"chapter 26","chapter twenty-six","26",}):"chapter 26 \"Sentients\"
	       Building Sentient Non-Player Characters
		   The Nightmare IV Object Library
		 written by Descartes of Borg 951127

One thing most everyone wants to see are monsters that react more
intelligently to user input.  The fact is, however, that most monsters
in the game only need a small, basic behaviour set.  Nevertheless, in
order to make an area interesting, there should be some monsters which
stand out as unique and purposeful.  The problem about building such
monsters is that they use a lot of processing time.

In order to make sure most monsters which do not need such
intelligence do not waste processing time on such activities, the
Nightmare Object Library separates non-player characters into two
classes: dumb monsters, which are basic mindless automata and
sentients, monsters which react more intelligently to their
environment.

This document describes sentients.  Before looking at this document,
it is highly recommended that you be familiar with the document
/doc/build/NPC which details non-player characters.  Sentients are
non-player characters, so everthing which applies to non-player
characters also applies to sentients.

				*****

Currently, a few basic behaviours distinguish sentients from normal
npcs.  Those behaviours are the ability to intelligently move about
the mud and to react to user speech.  Nightmare thus provides the
following functions to allow you to easily have an sentient enact
those behaviours:

	mapping SetTalkResponses(mapping mp);
	mixed AddTalkResponse(string str, mixed val);
	int RemoveTalkResponse(string str);

	mapping SetCommandResponses(mapping mp);
	mixed AddCommandResponse(string str, mixed val);
	int RemoveCommandResponse(string str);

	varargs int SetWander(int speed, string *path, int recurse);
	string *SetWanderPath(string *path);

	int SetWanderRecurse(int x);

	int SetWanderSpeed(int x);

				*****

Making NPCs react to user speech

You may want to have NPCs react to things players say.  To that end,
the following functions exist:

	mapping SetTalkResponses(mapping mp);
	mixed AddTalkResponse(string str, mixed val);
	int RemoveTalkResponse(string str);

Function: mapping SetTalkResponses(mapping mp)
Example: SetTalkResponses( ([ \"square\" : \"The square is east of here.\",
            \"house\" : \"Isn't that an ugly house?\" ]) );

This function allows you to set a list of responses to given phrases.
For example, if you put this code in a sentient and a player said
\"Where is the square?\" or \"Your frog is certainly square.\", your NPC
would have said \"The square is east of here.\".  Note therefore that
the NPC is only looking for the keys you place in there.  You could
have restricted it to \"where is the square\" instead of \"square\", but
then someone asking \"Where's the square\" would be missed.  

Also note that phrases should be in lower case.  It will match to
upper case words automatically.

Finally, you can either give a string or a function as the match to a
phrase.  If the match is a string, the NPC simply says the string in
the NPC's native tongue.  If, however, the match is a function, that
function will get called.

*****

Function: mixed AddTalkResponse(string str, mixed val);
Example: AddTalkResponse(\"in the house\", (: HouseFunc :));

Matches an individual phrase to a string or function.  As with
SetTalkResponses(), if the match is a string, the NPC simply says the
string in response to the phrase.  If it is a function, that function
gets called.

*****

Function: int RemoveTalkResponse(string str);
Example: RemoveTalkResponse(\"house\");

Removes the previous set or added talk response from the NPC.

				*****

Making NPCs react to user directives

Nightmare supports a special command, the \"ask\" command.  A player may
use the ask command to ask an NPC to perform a certain task.  For
example, \"ask the healer to mend my right leg\".  There is a special
event in NPC's which responds to this called eventAsk().  In order to
make responding to this easier, however, Nightmare has the
CommandResponse functions.  The command response functions allow NPC's
to respond based on commands, like \"mend\".  

*****

Function: mapping SetCommandResponses(mapping mp);
Example: SetCommandResponses( ([ \"heal\", \"I cannot heal people\" ]) );

Allows you to match commands to either strings or functions.  Matched
functions get called with the command as the first argument, and
command arguments as the second argument.  For example, if you had:
	SetCommandResponses(\"give\", (: give :));
Your give() function would get called with \"give\" as the first
argument and \"me the sword\" as the second argument in response to a
player issuing the command \"ask the monster to give me the sword\".

*****

Function: mixed AddCommandResponse(string str, mixed val);
Example: AddCommandResponse(\"give\", (: give :));

This allows you to add to the list of commands to which the NPC
responds.  The NPC responds to those commands as outlined for
SetCommandResponses().

*****

Function: int RemoveCommandResponse(string str);
Example: RemoveCommandResponse(\"give\")

Removes a previously set command response.

				*****

Making NPCs move about the game intelligently

A sticky subject on most muds is that of wandering monsters.  When
done poorly, they can waste resources to a great degree.  Nightmare,
however, works to avoid wasting resources while getting the most out
of allowing monsters to move about.

Nightmare supports two types of wandering monsters: those which have
pre-determined paths and others which are true wanderers.  True
wanderers, those who simply randomly choose paths are subject to the
following restrictions:
	They may not move into rooms not yet loaded in memory.
	They will not try to open closed doors.
The first restriction is the most important to note.  This means that
the NPC will not wander into rooms that have not been recently visited
by some player.  This avoids the problem NPCs cause on many muds of
uselessly loading rooms that only the monster will ever see.

Monsters given specific paths to wander are not subject to the above
restrictions.  Of course, they cannot wander through closed doors.
But you can make part of their path to open a closed door.  In
addition, since such monsters have very specific sets of rooms into
which they can travel, they are not in danger of needlessly loading a
zillion rooms.

*****

Function: varargs int SetWander(int speed, string *path, int recurse);
Examples:
	SetWander(5);
	SetWander(5, ({ \"go north\", \"open door\", \"enter hut\", \"go west\" }));
	SetWander(5, ({ \"go north\", \"open door\", \"enter hut\", \"go west\",
                       \"go south\" }), 1);

This is the function you will almost always use in create() to make a
sentient wander.  Only one of the three possible arguments is
mandatory, that being the speed.  The speed is simply the number of
heart beats between attempts to move.  Thus, the higher the number,
the slower the movement of the monster.

The second argument, if given, is a list of commands which will be
executed in order by the monster.  If it is not given, the monster
will be assumed to be a true wanderer.  In other words, the first time
the monster tries to wander, the monster will \"go north\".  The second
time, he will \"open door\".  The third, he will \"enter hut\", etc.  

The third argument is either 1 or 0.  If 1, that means once the
monster has completed the path, it will use the first command in the
list the next time it tries to wander.  If 0, it will cease to issue
commands once it has cycled through the list.

You might note that between the time the above monster opens the door
and enters the hut, somebody could come along and shut the door.  How
can you deal with that?  You could do:
	SetWander(5, ({ \"go north\", ({ \"open door\", \"enter hut\" }) }));
You will notice here that the second member of the command array is
itself an array instead of a string.  In that case, all members of
that array get executed as part of that wander.  In this case it helps
make sure no one closes the door between when the monster tries to
open it and when it tries to pass through the door.

For even more flexibility, you can make elements of the array into
functions.  Instead of executing a command in a wander turn, the
function you provide instead gets called.  For example:
	SetWander(5, ({ \"go north\", (: kill_anyone :), \"go south\" }), 1);
Where the function kill_anyone() has the monster kill any players in
that room.  Thus, this monster sits in its room and occasionally pops
its head one room to the north to kill anyone sitting there.

*****

Function: string *SetWanderPath(string *path);
Example: SetWanderPath(({ \"go north\", \"go south\" }))

Allows you to set the monster's wander path independent of other
settings.  The wander path will never get executed, however, unless
the monster's wander speed is greater than 0.

*****

Function: int SetWanderRecurse(int x);
Example: SetWanderRecurse(1);

Allows you to make the monster's wander path recurse independent of
other settings.  This is meaningless, however, unless the monster's
wander speed is greater than 0 and a wander path is set for it.

*****

Function: int SetWanderSpeed(int x);
Example: SetWanderSpeed(5);

Allows you to set the monster's wander speed independent of other
settings.  This is NOT the same as SetWander(5).  SetWander() will
clear out any previous wander path and wander recurse settings.  This
function has no effect on the monster's wander path or wander recurse.

",({"chapter 5","chapter five","5",}):"chapter 5 \"The Basics of Inheritance\"
                           LPC Basics
                  Written by Descartes of Borg
                  first edition: 23 april 1993
                  second edition: 01 july 1993

CHAPTER 5: The Basics of Inheritance

5.1 Review
You should now understand the basic workings of functions.  You should be
able to declare and call one.  In addition, you should be able to recognize
function definitions, although, if this is your first experience with LPC,
it is unlikely that you will as yet be able to define your own functions.
There functions form the basic building blocks of LPC objects.  Code
in them is executed when another function makes a call to them.  In making
a call, input is passed from the calling function into the execution of
the called one.  The called function then executes and returns a value
of a certain data type to the calling function.  Functions which return
no value are of type void.

After examining your workroom code, it might look something like this
(depending on the mudlib):

-----
inherit \"/std/room\";

void create() {
    ::create();
    SetProperty(\"light\", 2);
    SetProperty(\"indoors\", 1);
    set(\"short\", \"Descartes' Workroom\");
    set(\"long\", \"This is where Descartes works.\\nIt is a cube.\\n\");
    SetExits( ({ \"/domains/standard/square\" }), ({ \"square\" }) );
}
-----

If you understand the entire textbook to this point, you should recognize
of the code the following:
    1) create() is the definition of a function (hey! he did not declare it)
    2) It makes calls to SetProperty(), set(), and SetExits(), none
       of which are declared or defined in the code.
    3) There is a line at the top that is no variable or function declaration
       nor is it a function definition!

This chapter will seek to answer the questions that should be in your head
at this point:
    1) Why is there no declaration of create()?
    2) Where are the functions SetProperty(), set(), and SetExits() declared
       and defined?
    3) What the hell is that line at the top of the file?

5.2 Object oriented programming
Inheritance is one of the properties which define true object oriented
programming (OOP).  It allows you to create generic code which can be used
in many different ways by many different programs.  What a mudlib does is
create these generalized files (objects) which you use to make very specific
objects.

If you had to write the code necessary for you to define the workroom above,
you would have to write about 1000 lines of code to get all the functionality
of the room above.  Clearly that is a waste of disk space.  In addition,
such code does not interact well with players and other rooms since every
creator is making up his or her own functions to perform the functionality
of a room.  Thus, what you might use to write out the room's long description,
GetLong(), another wizard might be calling long().  This is the primary
reason mudlibs are not compatible, since they use different protocols for
object interaction.

OOP overcomes these problems.  In the above workroom, you inherit the
functions already defined in a file called \"/std/room.c\".  It has all
the functions which are commonly needed by all rooms defined in it.  When
you get to make a specific room, you are taking the general functionality
of that room file and making a unique room by adding your own function,
create().

5.3 How inheritance works
As you might have guessed by now, the line:

-----
inherit \"/std/room\";
-----

has you inherit the functionality of the room \"/std/room.c\".  By inheriting
the functionality, it means that you can use the functions which have
been declared and defined in the file \"/std/room.c\"  In the Nightmare Mudlib,
\"/std/room.c\" has, among other functions, SetProperty(), set(), and
SetExits() declared and defined.  In your function create(), you are
making calls to those functions in order to set values you want your
room to start with.  These values make your room different from others, yet
able to interact well with other objects in memory.

In actual practice, each mudlib is different, and thus requires you to use
a different set of standard functions, often to do the same thing.  It is
therefore beyond the scope of this textbook even to describe what
functions exist and what they do.  If your mudlib is well documented,
however, then (probably in /doc/build) you will have tutorials on how
to use the inheritable files to create such objects.  These tutorials
should tell you what functions exist, what input they take, the data
type of their output, and what they do.

5.4 Chapter summary
This is far from a complete explanation of the complex subject of inheritance.
The idea here is for you to be able to understand how to use inheritance in
creating your objects.  A full discussion will follow in a later textbook.
Right now you should know the following:
    1) Each mudlib has a library of generic objects with their own general
       functions used by creators through inheritance to make coding objects
       easier and to make interaction between objects smoother.
    2) The functions in the inheritable files of a mudlib vary from mudlib
       to mudlib.  There should exist documentation on your mud on how to
       use each inheritable file.  If you are unaware what functions are
       available, then there is simply no way for you to use them.  Always
       pay special attention to the data types of the input and the data
       types of ay output.
    3) You inherit the functionality of another object through the line:

-----
inherit \"filename\";
-----
       
       where filename is the name of the file of the object to be inherited.
       This line goes at the beginning of your code.

Note:
You may see the syntax ::create() or ::init() or ::reset() in places.
You do not need fully to understand at this point the full nuances of this,
but you should have a clue as to what it is. The \"::\" operator is a way
to call a function specifically in an inherited object (called the scope
resolution operator).  For instance, most muds' room.c has a function
called create().  When you inherit room.c and configure it, you are doing
what is called overriding the create() function in room.c.  This means
that whenever ANYTHING calls create(), it will call *your* version and not
the one in room.c.  However, there may be important stuff in the room.c
version of create().  The :: operator allows you to call the create() in
room.c instead of your create().
An example:

-----
#1

inherit \"/std/room\";

void create() { create(); }
-----

-----
#2

inherit \"/std/room\";

void create() { ::create(); }
-----

Example 1 is a horror.  When loaded, the driver calls create(), and then
create() calls create(), which calls create(), which calls create()...
In other words, all create() does is keep calling itself until the driver
detects a too deep recursion and exits.

Example 2 is basically just a waste of RAM, as it is no different from room.c
functionally.  With it, the driver calls its create(), which in turn calls
::create(), the create() in room.c.  Otherwise it is functionally
exactly the same as room.c.
",({"chapter 2","chapter two","2",}):"chapter 2 \"The LPC Program\"
                           LPC Basics
                  Written by Descartes of Borg
                  first edition: 23 april 1993
                  second edition: 16 june 1993

CHAPTER 2: The LPC Program

2.1 About programs
The title of this chapter of the textbook is actually poorly named, since
one does not write programs in LPC.  An LPC coder instead writes *objects*.
What is the difference?  Well, for our purposes now, the difference is
in the way the file is executed.  When you \"run\" a program, execution
begins at a definite place in the program.  In other words, there
is a place in all programs that is noted as the beginning where program
execution starts.  In addition, programs have definite end points,
so that when execution reaches that point, the execution of the program
terminates.  So, in short, execution of a program runs from a definite
beginning point through to a definite end point.  This is not so with
LPC objects.

With muds, LPC objects are simply distinct parts of the C program which
is running the game (the driver).  In other words, execution of the mud
program begins and ends in the driver.  But the driver in fact does
very little in the way of creating the world you know when you play
a mud.  Instead, the driver relies heavily on the code created in LPC,
executing lines of the objects in the mud as needed.  LPC objects thus
have no place that is necessarily the beginning point, nor do they
have a definite ending point.

Like other programming languages, an LPC \"program\" may be made up of
one or more files.  For an LPC object to get executed, it simple
needs to be loaded into the driver's memory.  The driver will call lines
from the object as it needs according to a structure which will be
defined throughout this textbook.  The important thing you need to
understand at this point is that there is no \"beginning\" to an LPC
object in terms of execution, and there is no \"end\".

2.2 Driver-mudlib interaction
As I have mentioned earlier, the driver is the C program that runs on
the host machine.  It connects you into the game and processes LPC code.
Note that this is one theory of mud programming, and not necessarily
better than others.  It could be that the entire game is written in C.
Such a game would be much faster, but it would be less flexible in
that wizards could not add things to the game while it was running. This
is the theory behind DikuMUDs.  Instead, LPMUDs run on the theory that
the driver should in no define the nature of the game, that the nature
of the game is to be decided by the individuals involved, and that
you should be able to add to the game *as it is being played*.  This
is why LPMUDs make use of the LPC programming language.  It allows
you to define the nature of the game in LPC for the driver to read and
execute as needed.  It is also a much simpler language to understand
than C, thus making the process of world creation open to a greater
number of people.

Once you have written a file in LPC (assuming it is corrent LPC ), it justs
sits there on the host machine's hard drive until something in the game
makes reference to it.  When something in the game finally does make
reference to the object, a copy of the file is loaded into memory and
a special *function* of that object is called in order to initialize
the values of the variables in the object.  Now, do not be concerned
if that last sentence went right over your head, since someone brand
new to programming would not know what the hell a function or a variable
is.  The important thing to understand right now is that a copy of the
object file is taken by the driver from the machine's hard drive and
stored into memory (since it is a copy, multiple versions of that
object may exist).  You will later understand what a function is, what
a variable is, and exactly how it is something in the game made reference
to your object.

2.3 Loading an object into memory
Although there is no particular place in an object code that must exist
in order for the driver to begin executing it, there is a place for which
the driver will search in order to initialize the object.  On compat 
drivers, it is the function called reset().  On native muds it is the
function called create().

LPC objects are made up of variables (values which can change) and
functions which are used to manipulate those variables.  Functions
manipulate variables through the use of LPC grammatical structures,
which include calling other functions, using externally defined
functions (efuns), and basic LPC expressions and flow control 
mechanisms.

Does that sound convoluted?  First lets start with a variable.  A
variable might be something like: level.  It can \"vary\" from sitation
to situation in value, and different things use the value of the player's
level to make different things happen.  For instance, if you are a
level 19 player, the value of the variable level will be 19.  Now
if your mud is on the old LPMud 2.4.5 system where levels 1-19 are
players and 20+ are wizards, things can ask for your level value to
see if you can perform wizard type actions.  Basically, each object
in LPC is a pile of variables with values which change over time.
Things happen to these objects based on what values its variables
hold.  Often, then things that happen cause the variables to change.

So, whenever an object in LPC is referenced by another object currently
in memory, the driver searches to see what places for values the
object has (but they have no values yet).  Once that is done, the driver
calls a function in the object called reset() or create() (depending
on your driver) which will set up the starting values for the object's
variables.  It is thus through *calls* to *functions* that variable
values get manipulated.

But create() or reset() is NOT the starting place of LPC code, although
it is where most LPC code execution does begin.  The fact is, those
functions need not exist.  If your object does just fine with its
starting values all being NULL pointers (meaning, for our purposes
here, 0), then you do not need a create() or reset() function.  Thus
the first bit of execution of the object's code may begin somewhere
completely different.

Now we get to what this chapter is all about.  The question: What
consists a complete LPC object?  Well, an LPC object is simply
one or more functions grouped together manipulating 0 or more
variables.  The order in which functions are placed in an object
relative to one another is irrelevant.  In other words:

-----
void init() { add_action(\"smile\", \"smile\"); }

void create() { return; }

int smile(string str) { return 0; }
-----

is exactly the same as:

-----
void create() { return; }

int smile(string str) { return 0; }

void init() { add_action(\"smile\", \"smile\"); }
_____

Also important to note, the object containing only:

-----
void nonsense() {}
-----

is a valid, but trivial object, although it probably would not interact
properly with other objects on your mud since such an object has no
weight, is invisible, etc..

2.4 Chapter summary
LPC code has no beginning point or ending point, since LPC code is used
to create objects to be used by the driver program rather than create
individual programs.  LPC objects consist of one or more functions whose
order in the code is irrelevant, as well as of zero or more variables whose
values are manipulated inside those functions.  LPC objects simply sit
on the host machine's hard driver until referenced by another object in
the game (in other words, they do not really exist).  Once the object
is referenced, it is loaded into the machine's memory with empty
values for the variables.  The function reset() in compat muds or
create() in native muds is called in that object if it exists to allow
the variables to take on initial values.  Other functions in the object
are used by the driver and other objects in the game to allow interaction
among objects and the manipulation of the LPC variables.

A note on reset() and create():
create() is only used by muds in native mode (see the textbook Introduction
for more information on native mode vs. compat mode).  It is only used
to initialize newly referenced objects.

reset() is used by both muds in compat mode and native mode.  In compat
mode, reset() performs two functions.  First, it is used to initialize
newly referenced objects.  In addition, however, compat mode muds use
reset() to \"reset\" the object.  In other words, return it to its initial
state of affairs.  This allows monsters to regenerate in a room and doors
to start back in the shut position, etc..  Native mode muds use reset()
to perform the second function (as its name implies).

So there are two important things which happen in LP style muds which
cause the driver to make calls to functions in objects.  The first is
the creation of the object.  At this time, the driver calls a function
to initalize the values in the object.  For compat mode muds, this
is performed by the function named reset() (with an argument of 0,
more on this later though).  For muds running in native mode, this is
performed by the function create().

The second is the returning of the room to some base state of affairs.
This base set of affairs may or may not be different from the initial
state of affairs, and certainly you would not want to take up time
doing redundant things (like resetting variables that never change).
Compat mode muds nevertheless use the same function that was used to
create the object to reset it, that being reset().  Native mode muds,
who use create() to create the room, instead use reset() to reset it.
All is not lost in compat mode though, as there is a way to tell the
difference between creation and resetting.  For reset purposes, the
driver passes either 1 or the reset number as an argument to reset()
in compat mode.  Now this is meaningless to you now, but just keep in
mind that you can in fact tell the difference in compat mode.  Also
keep in mind that the argment in the creation use of reset is 0 and
the argument in the reset use is a nonzero number.
",({"chapter 11","chapter eleven","11",}):"chapter 11 \"Complex Data Types\"
Intermediate LPC
Descartes of Borg
November 1993

                        Chapter 3: Complex Data Types

3.1 Simple Data Types
In the textbook LPC Basics, you learned about the common, basic LPC
data types: int, string, object, void.  Most important you learned that
many operations and functions behave differently based on the data type
of the variables upon which they are operating.  Some operators and
functions will even give errors if you use them with the wrong data
types.  For example, \"a\"+\"b\" is handled much differently than 1+1. 
When you ass \"a\"+\"b\", you are adding \"b\" onto the end of \"a\" to get
\"ab\".  On the other hand, when you add 1+1, you do not get 11, you get
2 as you would expect.

I refer to these data types as simple data types, because they atomic in
that they cannot be broken down into smaller component data types. 
The object data type is a sort of exception, but you really cannot refer
individually to the components which make it up, so I refer to it as a
simple data type.

This chapter introduces the concept of the complex data type, a data type
which is made up of units of simple data types.  LPC has two common
complex data types, both kinds of arrays.  First, there is the traditional
array which stores values in consecutive elements accessed by a number
representing which element they are stored in.  Second is an associative
array called a mapping.  A mapping associates to values together to
allow a more natural access to data.

3.2 The Values NULL and 0
Before getting fully into arrays, there first should be a full understanding
of the concept of NULL versus the concept of 0.  In LPC, a null value is
represented by the integer 0.  Although the integer 0 and NULL are often
freely interchangeable, this interchangeability often leads to some great
confusion when you get into the realm of complex data types.  You may
have even encountered such confusion while using strings.

0 represents a value which for integers means the value you add to
another value yet still retain the value added.  This for any addition
operation on any data type, the ZERO value for that data type is the value
that you can add to any other value and get the original value.  Thus:   A
plus ZERO equals A where A is some value of a given data type and
ZERO is the ZERO value for that data type.  This is not any sort of
official mathematical definition.  There exists one, but I am not a
mathematician, so I have no idea what the term is.  Thus for integers, 0
is the ZERO value since 1 + 0 equals 1.

NULL, on the other hand, is the absence of any value or meaning.  The
LPC driver will interpret NULL as an integer 0 if it can make sense of it
in that context.  In any context besides integer addition, A plus NULL
causes an error.  NULL causes an error because adding valueless fields
in other data types to those data types makes no sense.

Looking at this from another point of view, we can get the ZERO value
for strings by knowing what added to \"a\" will give us \"a\" as a result. 
The answer is not 0, but instead \"\".  With integers, interchanging NULL
and 0 was acceptable since 0 represents no value with respect to the
integer data type.  This interchangeability is not true for other data types,
since their ZERO values do not represent no value.  Namely, \"\"
represents a string of no length and is very different from 0.  

When you first declare any variable of any type, it has no value.  Any
data type except integers therefore must be initialized somehow before
you perform any operation on it.  Generally, initialization is done in the
create() function for global variables, or at the top of the local function
for local variables by assigning them some value, often the ZERO value
for that data type.  For example, in the following code I want to build a
string with random words:

string build_nonsense() {
    string str;
    int i;

    str = \"\"; /* Here str is initialized to the string
ZERO value */
    for(i=0; i<6; i++) {
        switch(random(3)+1) {
            case 1: str += \"bing\"; break;
            case 2: str += \"borg\"; break;
            case 3: str += \"foo\"; break;
        }
        if(i==5) str += \".\\n\";
        else str += \" \";
    }
    return capitalize(str);
}

If we had not initialized the variable str, an error would have resulted
from trying to add a string to a NULL value.  Instead, this code first
initializes str to the ZERO value for strings, \"\".  After that, it enters a
loop which makes 6 cycles, each time randomly adding one of three
possible words to the string.  For all words except the last, an additional
blank character is added.  For the last word, a period and a return
character are added.  The function then exits the loop, capitalizes the
nonsense string, then exits.

3.3 Arrays in LPC
An array is a powerful complex data type of LPC which allows you to
access multiple values through a single variable.  For instance,
Nightmare has an indefinite number of currencies in which players may
do business.  Only five of those currencies, however, can be considered
hard currencies.  A hard currency for the sake of this example is a
currency which is readily exchangeable for any other hard currency,
whereas a soft currency may only be bought, but not sold.  In the bank,
there is a list of hard currencies to allow bank keepers to know which
currencies are in fact hard currencies.  With simple data types, we would
have to perform the following nasty operation for every exchange
transaction:

int exchange(string str) {
    string from, to;
    int amt;

    if(!str) return 0;
    if(sscanf(str, \"%d %s for %s\", amt, from, to) != 3)
      return 0;
    if(from != \"platinum\" && from != \"gold\" && from !=
      \"silver\" &&
      from != \"electrum\" && from != \"copper\") {
        notify_fail(\"We do not buy soft currencies!\\n\");
        return 0;
    }
    ...
}

With five hard currencies, we have a rather simple example.  After all it
took only two lines of code to represent the if statement which filtered
out bad currencies.  But what if you had to check against all the names
which cannot be used to make characters in the game?  There might be
100 of those; would you want to write a 100 part if statement?
What if you wanted to add a currency to the list of hard currencies?  That
means you would have to change every check in the game for hard
currencies to add one more part to the if clauses.  Arrays allow you
simple access to groups of related data so that you do not have to deal
with each individual value every time you want to perform a group
operation.

As a constant, an array might look like this:
    ({ \"platinum\", \"gold\", \"silver\", \"electrum\", \"copper\" })
which is an array of type string.  Individual data values in arrays are
called elements, or sometimes members.  In code, just as constant
strings are represented by surrounding them with \"\", constant arrays are
represented by being surrounded by ({ }), with individual elements of
the array being separated by a ,.

You may have arrays of any LPC data type, simple or complex.  Arrays
made up of mixes of values are called arrays of mixed type.  In most
LPC drivers, you declare an array using a throw-back to C language
syntax for arrays.  This syntax is often confusing for LPC coders
because the syntax has a meaning in C that simply does not translate into
LPC.  Nevertheless, if we wanted an array of type string, we would
declare it in the following manner:

string *arr;

In other words, the data type of the elements it will contain followed by
a space and an asterisk.  Remember, however, that this newly declared
string array has a NULL value in it at the time of declaration.

3.4 Using Arrays
You now should understand how to declare and recognize an array in
code.  In order to understand how they work in code, let's review the
bank code, this time using arrays:

string *hard_currencies;

int exchange(string str) {
    string from, to;
    int amt;

    if(!str) return 0;
    if(sscanf(str, \"%d %s for %s\", amt, from, to) != 3)
return 0;
    if(member_array(from, hard_currencies) == -1) {
        notify_fail(\"We do not buy soft currencies!\\n\");
        return 0;
    }
    ...
}

This code assumes hard_currencies is a global variable and is initialized
in create() as:
    hard_currencies = ({ \"platinum\", \"gold\", \"electrum\", \"silver\",
   \"copper\" });
Ideally, you would have hard currencies as a #define in a header file for
all objects to use, but #define is a topic for a later chapter.

Once you know what the member_array() efun does, this method
certainly is much easier to read as well as is much more efficient and
easier to code.  In fact, you can probably guess what the
member_array() efun does:  It tells you if a given value is a member of
the array in question.  Specifically here, we want to know if the currency
the player is trying to sell is an element in the hard_curencies array. 
What might be confusing to you is, not only does member_array() tell us
if the value is an element in the array, but it in fact tells us which element
of the array the value is.

How does it tell you which element?  It is easier to understand arrays if
you think of the array variable as holding a number.  In the value above,
for the sake of argument, we will say that hard_currencies holds the
value 179000.  This value tells the driver where to look for the array
hard_currencies represents.  Thus, hard_currencies points to a place
where the array values may be found.  When someone is talking about
the first element of the array, they want the element located at 179000. 
When the object needs the value of the second element of the array, it
looks at 179000 + one value, then 179000 plus two values for the third,
and so on.  We can therefore access individual elements of an array by
their index, which is the number of values beyond the starting point of
the array we need to look to find the value.  For the array
hard_currencies array:
\"platinum\" has an index of 0.
\"gold\" has an index of 1.
\"electrum\" has an index of 2.
\"silver\" has an index of 3.
\"copper\" has an index of 4.

The efun member_array() thus returns the index of the element being
tested if it is in the array, or -1 if it is not in the array.  In order to
reference an individual element in an array, you use its index number in
the following manner:
array_name[index_no]
Example:
hard_currencies[3]
where hard_currencies[3] would refer to \"silver\".

So, you now should now several ways in which arrays appear either as
a whole or as individual elements.  As a whole, you refer to an array
variable by its name and an array constant by enclosing the array in ({ })
and separating elements by ,.  Individually, you refer to array variables
by the array name followed by the element's index number enclosed in
[], and to array constants in the same way you would refer to simple data
types of the same type as the constant.  Examples:

Whole arrays:
variable:  arr
constant: ({ \"platinum\", \"gold\", \"electrum\", \"silver\", \"copper\" })

Individual members of arrays:
variable: arr[2]
constant: \"electrum\"

You can use these means of reference to do all the things you are used to
doing with other data types.  You can assign values, use the values in
operations, pass the values as parameters to functions, and use the
values as return types.  It is important to remember that when you are
treating an element alone as an individual, the individual element is not
itself an array (unless you are dealing with an array of arrays).  In the
example above, the individual elements are strings.  So that:
    str = arr[3] + \" and \" + arr[1];
will create str to equal \"silver and gold\".  Although this seems simple
enough, many people new to arrays start to run into trouble when trying
to add elements to an array.  When you are treating an array as a whole
and you wish to add a new element to it, you must do it by adding
another array.

Note the following example:
string str1, str2;
string *arr;

str1 = \"hi\";
str2 = \"bye\";
/* str1 + str2 equals \"hibye\" */
arr = ({ str1 }) + ({ str2 });
/* arr is equal to ({ str1, str2 }) */
Before going any further, I have to note that this example gives an
extremely horrible way of building an array.  You should set it: arr = ({
str1, str2 }).  The point of the example, however, is that you must add
like types together.  If you try adding an element to an array as the data
type it is, you will get an error.  Instead you have to treat it as an array of
a single element.

3.5 Mappings
One of the major advances made in LPMuds since they were created is
the mapping data type.  People alternately refer to them as associative
arrays.  Practically speaking, a mapping allows you freedom from the
association of a numerical index to a value which arrays require. 
Instead, mappings allow you to associate values with indices which
actually have meaning to you, much like a relational database.

In an array of 5 elements, you access those values solely by their integer
indices which cover the range 0 to 4.  Imagine going back to the example
of money again.  Players have money of different amounts and different
types.  In the player object, you need a way to store the types of money
that exist as well as relate them to the amount of that currency type the
player has.  The best way to do this with arrays would have been to
store an array of strings representing money types and an array of
integers representing values in the player object.  This would result in
CPU-eating ugly code like this:

int query_money(string type) {
    int i;

    i = member_array(type, currencies);
    if(i>-1 && i < sizeof(amounts))  /* sizeof efun
returns # of elements */
        return amounts[i];
    else return 0;
}

And that is a simple query function.  Look at an add function:

void add_money(string type, int amt) {
    string *tmp1;
    int * tmp2;
    int i, x, j, maxj;
    
    i = member_array(type, currencies);
    if(i >= sizeof(amounts)) /*  corrupt data, we are in
      a bad way */
        return;
    else if(i== -1) {
        currencies += ({ type });
        amounts += ({ amt });
        return;
    }
    else {
        amounts[i] += amt;
        if(amounts[i] < 1) {
            tmp1 = allocate(sizeof(currencies)-1);
            tmp2 = allocate(sizeof(amounts)-1);
            for(j=0, x =0, maxj=sizeof(tmp1); j < maxj;
              j++) {
                if(j==i) x = 1;
                tmp1[j] = currencies[j+x];
                tmp2[j] = amounts[j+x];
            }
            currencies = tmp1;
            amounts = tmp2;
        }
    }
}

That is really some nasty code to perform the rather simple concept of
adding some money.  First, we figure out if the player has any of that
kind of money, and if so, which element of the currencies array it is. 
After that, we have to check to see that the integrity of the currency data
has been maintained.  If the index of the type in the currencies array is
greater than the highest index of the amounts array, then we have a
problem since the indices are our only way of relating the two arrays. 
Once we know our data is in tact, if the currency type is not currently
held by the player, we simply tack on the type as a new element to the
currencies array and the amount as a new element to the amounts array. 
Finally, if it is a currency the player currently has, we just add the
amount to the corresponding index in the amounts array.  If the money
gets below 1, meaning having no money of that type, we want to clear
the currency out of memory.

Subtracting an element from an array is no simple matter.  Take, for
example, the result of the following:

string *arr;

arr = ({ \"a\", \"b\", \"a\" });
arr -= ({ arr[2] });

What do you think the final value of arr is? Well, it is:
    ({ \"b\", \"a\" })
Subtracting arr[2] from the original array does not remove the third
element from the array.  Instead, it subtracts the value of the third
element of the array from the array.  And array subtraction removes the
first instance of the value from the array.  Since we do not want to be
forced on counting on the elements of the array as being unique, we are
forced to go through some somersaults to remove the correct element
from both arrays in order to maintain the correspondence of the indices
in the two arrays.

Mappings provide a better way.  They allow you to directly associate the
money type with its value.  Some people think of mappings as arrays
where you are not restricted to integers as indices.  Truth is, mappings
are an entirely different concept in storing aggregate information.  Arrays
force you to choose an index which is meaningful to the machine for
locating the appropriate data.  The indices tell the machine how many
elements beyond the first value the value you desire can be found.  With
mappings, you choose indices which are meaningful to you without
worrying about how that machine locates and stores it.

You may recognize mappings in the following forms:

constant values:
whole: ([ index:value, index:value ]) Ex: ([ \"gold\":10, \"silver\":20 ])
element:  10

variable values:
whole:    map   (where map is the name of a mapping variable)
element: map[\"gold\"]

So now my monetary functions would look like:

int query_money(string type) { return money[type]; }

void add_money(string type, int amt) {
    if(!money[type]) money[type] = amt;
    else money[type] += amt;
    if(money[type] < 1)
      map_delete(money, type);          /* this is for
          MudOS */
            ...OR... 
            money = m_delete(money, type)  /* for some
          LPMud 3.* varieties */
            ... OR... 
         m_delete(money, type);    /* for other LPMud 3.*
          varieties */
}

Please notice first that the efuns for clearing a mapping element from the
mapping vary from driver to driver.  Check with your driver's
documentation for the exact name an syntax of the relevant efun.

As you can see immediately, you do not need to check the integrity of
your data since the values which interest you are inextricably bound to
one another in the mapping.  Secondly, getting rid of useless values is a
simple efun call rather than a tricky, CPU-eating loop.  Finally, the
query function is made up solely of a return instruction. 

You must declare and initialize any mapping before using it. 
Declarations look like:
mapping map;
Whereas common initializations look like:
map = ([]);
map = allocate_mapping(10)   ...OR...   map = m_allocate(10);
map = ([ \"gold\": 20, \"silver\": 15 ]);

As with other data types, there are rules defining how they work in
common operations like addition and subtraction:
    ([ \"gold\":20, \"silver\":30 ]) + ([ \"electrum\":5 ]) 
gives:
    ([\"gold\":20, \"silver\":30, \"electrum\":5])   
Although my demonstration shows a continuity of order, there is in fact
no guarantee of the order in which elements of mappings will stored. 
Equivalence tests among mappings are therefore not a good thing.

3.6 Summary
Mappings and arrays can be built as complex as you need them to be. 
You can have an array of mappings of arrays.  Such a thing would be
declared like this:

mapping *map_of_arrs;
which might look like:
({ ([ ind1: ({ valA1, valA2}), ind2: ({valB1, valB2}) ]), ([ indX:
({valX1,valX2}) ]) })

Mappings may use any data type as an index, including objects. 
Mapping indices are often referred to as keys as well, a term from
databases.  Always keep in mind that with any non-integer data type,
you must first initialize a variable before making use of it in common
operations such as addition and subtraction.  In spite of the ease and
dynamics added to LPC coding by mappings and arrays, errors caused
by failing to initialize their values can be the most maddening experience
for people new to these data types.  I would venture that a very high
percentage of all errors people experimenting with mappings and arrays
for the first time encounter are one of three error messages:
	Indexing on illegal type.
	Illegal index.
	Bad argument 1 to (+ += - -=) /* insert your favourite operator */
Error messages 1 and 3 are darn near almost always caused by a failure
to initialize the array or mapping in question.  Error message 2 is caused
generally when you are trying to use an index in an initialized array
which does not exist.  Also, for arrays, often people new to arrays will
get error message 3 because they try to add a single element to an array
by adding the initial array to the single element value instead of adding
an array of the single element to the initial array.  Remember, add only
arrays to arrays.

At this point, you should feel comfortable enough with mappings and
arrays to play with them.  Expect to encounter the above error messages
a lot when first playing with these.  The key to success with mappings is
in debugging all of these errors and seeing exactly what causes wholes
in your programming which allow you to try to work with uninitialized
mappings and arrays.  Finally, go back through the basic room code and
look at things like the SetE

Showing the first 100 KB of 601.9 KB. Download the archive for the full file.

Site Stats

Snippets: 1791
Codebases: 571