How to efficiently map tokens to code in a script interpreter?
- by lithander
I'm writing an interpreter for a simple scripting language where each line is a complete, executable command. (Like the instructions in assembler)
When parsing a line I have to map the requested command to actual code. My current solution looks like this:
std::string op, param1, param2;
//parse line, identify op, param1, param2
...
//call command specific code
if(op == "MOV")
ExecuteMov(AsNumber(param1));
else if(op == "ROT")
ExecuteRot(AsNumber(param1));
else if(op == "SZE")
ExecuteSze(AsNumber(param1));
else if(op == "POS")
ExecutePos((AsNumber(param1), AsNumber(param2));
else if(op == "DIR")
ExecuteDir((AsNumber(param1), AsNumber(param2));
else if(op == "SET")
ExecuteSet(param1, AsNumber(param2));
else if(op == "EVL")
...
The more commands are supported the more string comparisions I'll have to do to identify and call the associated method.
Can you point me to a more efficient implementation in the described scenario?