How to efficiently map tokens to code in a script interpreter?

Posted by lithander on Game Development See other posts from Game Development or by lithander
Published on 2012-11-30T22:16:30Z Indexed on 2012/11/30 23:23 UTC
Read the original article Hit count: 306

Filed under:
|

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?

© Game Development or respective owner

Related posts about c++

Related posts about Performance