On the Xojo forum a user asked if there was a way to execute a formula in Xojo. As pointed out in the conversation, Xojo includes an Evaluator example that does exactly that. It uses XojoScript and I thought it might be interesting to show how it works.
First, you can find the example by opening the Project Chooser (File->New), clicking “Examples” and then going to Advanced, XojoScript and selecting Evaluator.
Looking at the project you’ll see it has a primary Window (MainWindow) and a class called Evaluator. The Evaluator class is a subclass of XojoScript.
The way this project works is that it takes the formula that was entered in the TextField of the window and embeds it into XojoScript source and then runs the source to get the result, which is returned back to the window to display.
Take a look at the Eval method on the Evaluator class. It’s primary code is this:
Dim source As String source = "Dim expr As Variant = " + expression + EndOfLine + _ "If expr.IsNumeric Then " + EndOfLine + _ "mResult = Str(expr.DoubleValue)" + EndOfLine + _ "Else " + EndOfLine + _ "mResult = expr" +EndOfLine + _ "End If" Self.Source = source Self.Context = Self // So we can refer to Evaulator.mResult property in XojoScript Self.Run Return mResult
This code assigns the XojoScript source using the Source property and sets the Context property to itself which allows the XojoScript source to access the mResult property on the Evaluator class. Then it runs the XojoScript source.
This source assigns the formula to the line “Dim expr As Variant”, checks if the result is numeric and if it is, converts it to a string. The expression is then assigned to the mResult property so that it can be accessed outside the XojoScript source.
Which, back in the code for Eval, is what gets returned to the caller to display.
Of course, this does require that you pass in a valid Xojo expression that can be evaluated. Some example include:
- Hex(255), which returns FF
- Left(“XojoScript, 4), which returns Xojo
If you pass something that cannot be evaluated, you’ll get an error message which is displayed by either the CompilerError or RuntimeError events on the Evaluator class. Take a look at the ErrorCodeToString method to see a list of the possible errors. For example, the values below all generate an error:
- 54 + “test” displays a “Type Mismatch” error.
- “Dim i As Integer” displays a “Syntax does not make sense” error.
- PMT(45) displays “Unidentified identifier”
This sort of technique can be useful for projects where you want to dynamically run calculations that are not determined until the app is run.