Prismatic
Prismatic

Reputation: 3348

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:

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?

Upvotes: 0

Views: 434

Answers (2)

CapelliC
CapelliC

Reputation: 60034

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...
 }
}

Upvotes: 2

Thomas
Thomas

Reputation: 182000

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.

Upvotes: 1

Related Questions