Call Python or Lua from C++ to evaluate an expression, calculating unknown variables only if needed Call Python or Lua from C++ to evaluate an expression, calculating unknown variables only if needed python python

Call Python or Lua from C++ to evaluate an expression, calculating unknown variables only if needed


I don't know of any existing available library for handling this.

The usual approach would be to build an expression-tree and evaluate what is possible - similarly to constant folding in compilers:https://en.wikipedia.org/wiki/Constant_folding

One of the important aspects for that is to know the allowed values for variables, and thus the allowed partial evaluations, e.g. x*0 (and 0*x) is 0 if x is an integer, or finite floating point number, but cannot be evaluated if x is an IEEE floating number (since it could be Nan or infinity), or if x could be matrix since [1,1]*0 is [0,0] not the scalar 0.


One way is to parse the expression into a tree and evaluate the tree. Subexpressions for which all variables are known will be fully evaluated. The effect will be to simplify the tree.

In your example, the tree has && at the top with two subtrees, the left one being the tree for A>0. To evaluate the tree, we evaluate the left subtree, which returns -1, and so we don't need to evaluate the right subtree, because the operator is &&. The whole tree evaluates to false.


I don't understand exactly what you want to do or understand but I am OK with ivan_pozdeev about short-circuit evaluation and lazy evaluation.

A boolean expression is evaluate from the left to the right and when the result is known the evaluation stop and ignore what is on the right.

With Python:

E = "(A > 0) and (B > 5 or C > 10)"A = -1print(eval(E))

gives

False

But

E = "(A > 0) and (B > 5 or C > 10)"A = 1print(eval(E))

gives the error "name 'B' is not defined".