简体   繁体   中英

Evaluating scripted expression from C++

I have an app that needs to read in and evaluate expressions from a source file. I've been using muParser to do this so far. But now I've run into a case where I need simple loop support in the expression. I don't need the ability to call functions from the scripting language, or any other advanced functionality, literally just:

  • mathematical expressions (+,-,/,*,&, |, ~, etc)
  • logical expressions (!, ||, &&, etc)
  • conditionals (if,else..)
  • loops (for)

With muParser I parsed the expressions after reading them in, assigning variables as needed and then solving:

expr="[0] + [1]*256 - 40"

In the above example, I'd replace [0] and [1] with their corresponding variables, and could then solve. Now, I need something like this:

expr="for(i=0; i < 10; i+=2) {  if(i<=6) { [0] + [i]*256 -40; }  }"

All I'm doing in reality is parsing a bytestream. In the script, I refer to bytes as [byte] and bits as [byte][bit]. Could someone suggest what a good framework/scripting launguage would let me do something like this?

boost offers Spirit, but it's complex and overkill for your case. You could leverage the good muParser (last versione handle ternary 'if' operator), grabbing just the loop syntax with a regex parser: very easy to write. Let muParser handle each expression, and go interpreting the variable binding. Your parser could be something like:

class parse {
 parse(const char *expr) {
   if (match("for", "(", expr_init, ";" expr_test, ";", expr_after, ")", "{", body, "}"))
    for (eval(expr_init); eval(expr_test); eval(expr_after)) { bind_variables and run...}
   else
    go_old_style...
 }
}

Even though you don't seem to strictly need a full-blown scripting language, you're getting so close to it that this might be the easiest route to victory. Both Lua and Python are pretty easy to embed and call from a C(++) program, Lua slightly easier than Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM