Click to See Complete Forum and Search --> : Calling functions based on inputs


JoeLinkous
November 24th, 2007, 01:05 PM
Anyone ever play a MUD before? Usually, it's a telnet based game where you're in a fantasy world, and you enter commands to make your character move, chat, attack monsters, etc. Deep down, though, all that is happening is that the user inputs a command, the server does something based on that command, and the user gets an output. I wish to create a scalable command system.

A few commands are like the following:

attack <target> --- attack imp
sit <object (optional)> --- sit chair
move(direction) --- w
say <chat string> --- say hello thar buddy!

Each one has different base commands and uses the additional parameters in different ways.

I always think worst-case scenario, so when I see this problem, I think of the possibility of hundreds of different base commands, each one using parameters in different ways. Obviously, if I used an if/else chain to call the appropriate function for each command, it would take O(n) time which is not acceptable for a long list of commands.

There was another method I was thinking of, but I have no idea if it's even possible. Create a simple struct containing two things: the command name and the function name. I could then develop a search algorithm (possibly binary) to find the command, then execute the function accompanying it.

Any help would be greatly appreciated.

laserlight
November 24th, 2007, 01:15 PM
There was another method I was thinking of, but I have no idea if it's even possible. Create a simple struct containing two things: the command name and the function name. I could then develop a search algorithm (possibly binary) to find the command, then execute the function accompanying it.
That sounds possible. Another possibility is to use a std::map (or a hash map, with say, std::tr1::unordered_map, I think) to map the commands to say, their respective function pointers or perhaps function objects.

The function object approach may be better in the sense that once you have obtained the function object based on the command name, you can use operator overloading to call the correct operator() based on the arguments supplied by the user input.