0

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?

2 Answers 2

2

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...
 }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion -- but I feel like I might run into issues later with this route. Writing this is putting me on the path to writing my own interpreter, which I'll probably screw up :)
1

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.

2 Comments

Also good (although less widely used) is AngelScript (angelcode.com/angelscript), which has a very C++-like syntax.
I think I'm gonna bite the bullet and go with one of these choices. Thanks all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.