[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2 How to parse player commands

Parsing commands written by a player can be one of the more taxing tasks in programming the mud. It's also one of the more important ones, as intelligent command parsing can turn an otherwise annoying object into a useful one.

However, instead of having to do command parsing on your own there's a very neat efun called parse_command() available that'll take care of most of the chore for you. It's slightly tricky to use at first, but learning it is most worthwhile.

As you'll find, parse_command() looks slightly similar to sscanf() operating on word basis. Like sscanf() it will return values in its arguments (pass by reference) which might look slightly confusing but is necessary in this case.

The syntax is:

 
int parse_command(string command, object target|*targets, string pattern,
                  mixed arg, ...)

Let's take this one bit at a time.

The command above simply is what the player wrote; the text you want to parse for its contents.

The target or list of targets is the objects you want the command to operate on. I.e. the object or objects in which you expect the player to find the items he is manipulating.

The pattern is the text pattern you wish to match with the command.

The arguments is a list of arguments where the results of successful parsing will end up.

The efun will return a boolean value (1 or 0) denoting whether a match was possible or not.

Let's look at an example here: Assume you have coded an apple tree and you want the user to be able to pick one or more apples from the tree, or from the room the tree resides in which might have fallen down.

In the tree, you would add this code:

 
static int do_pick(string arg);  // Forward declaration

init()
{
    add_action(do_pick, "pick")
}

static int
do_pick(string arg)
{
    if (!parse_command(arg, environment(this_player()) + 
                            inventory(this_object()), 
                       "'apple' [from tree]
}


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated by Hekay Permer on April, 20 2005 using texi2html