I came up with a command lookup for a MUD-ish game I wrote that basically built a command tree built of nodes that were defined like:
Code:
struct command_node
{
char letter;
struct command_node *branches[26];
void (*func)();
}
Say you had the following commands: LOGON, LOGOFF, LOOK, LOOP
The tree would end up looking something like this:
Code:
L
/
O
/ \
G O
/ / \
O K P
/ \
N F
/
F
So to lookup a command you'd just loop through the user's input string and walk through the tree:
Code:
for each letter in input string
if treeroot->branches[letter] is not NULL, step into that node
...until you either came to a node->branches[letter] that was NULL indicating an unknown command or the end of the user's input. If the current node had a valid function pointer, it was called to handle the command. It's a little inefficient memory-wise to keep track of the command tree, but lookups were extremely fast. It definitely beat matching against each command, especially since the program supported about 150 different commands. Looking back, a hash table probably would be a lot simpler to implement.