Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » Storing and evaluating expressions

This thread is locked; no one can reply to it. rss feed Print
Storing and evaluating expressions
kenmasters1976
Member #8,794
July 2007

What's the best way to store an expression so that you can reevaluate it with, say, every update of your game's logic?. I'm talking of an expression like the following:

var = (1+2+3+XPos)*10

The expression is read from an external file and var and XPos are references to variables in my code. I already have code that can do the parsing of the expression and handle the references and I thought that storing the expression is Reverse Polish Notation would allow for easy evaluation and that is true for an expression like the one above but things get complicated as I try to introduce function calls where function arguments can be expressions as in:

var = 2*Min(E1, E2)

DanielH
Member #934
January 2001
avatar

For simple expressions, you could use RPN.

At one point, I created a math expression parser using trees. However, it's a bit complicated and might be overkill for what you do.

amarillion
Member #940
January 2001
avatar

RPN is one way to go

It's not too hard to write a recursive descent parser, I wrote at one point a parser that could handle most Excel expressions.

For a more thorough approach with functions and variables, you could look into embedding Lua - Lua is designed for that type of thing.

kenmasters1976
Member #8,794
July 2007

DanielH said:

At one point, I created a math expression parser using trees. However, it's a bit complicated and might be overkill for what you do.

Yeah, I've found a few libraries for handling expressions but either they're too robust (to the point that the library code and the code to integrate it with my game would result in more lines of code than my own), or they're too simple and can only handle simple math expressions but not variables or can handle variables defined in the expression but not variable references.

you could look into embedding Lua - Lua is designed for that type of thing.

Sounds interesting, I'll take a look into that.

Thanks.

Edgar Reynaldo
Major Reynaldo
May 2007
avatar

I have a function parser that handles unary, binary, and arbitrary function expressions. I based everything upon a base function class, with a constant function as well. It would be too hard to rip code out, but you can do it with some effort.

Go to: