Sometimes it is useful to evaluate a mathematical expression that is defined by the user at runtime. This is pretty easy to do using the EXECUTE routine, but EXECUTE is not allowed in applications running in the Virtual Machine. What to do?

This issue has been a problem for me before so I wrote a simple arithmetic parser (docs).

Evaluates a mathematical expression using the basic arithmetic operators +, -, *, /, and ^ along with parentheses for grouping and simple function calls of a single variable.

This routine is implemented with a recursive descent parser and does not use EXECUTE, so it is safe to use in the Virtual Machine.

For example, simple arithmetic expressions can be evaluated:

IDL> print, mg_evalexpr('1 + 2 + 3', error=error), error
6       0


Note that the ERROR keyword returns whether there was an error in evaluating the expression. Expressions can also take variables, if their values are provided via a structure or hash-like object:

IDL> print, mg_evalexpr('exp(i * pi)', { pi: !dpi, i: complex(0, 1) })
(      -1.0000000,   1.2246468e-16)


“Hash-like” here means that the object implements a hasKey method and subscripting via brackets like the IDL 8.0 Hash class.