Jan 20, 2008
On the REAL Software forums, someone posted a question about Eval functionality in REALbasic. In other languages, the Eval function is used to evaluate expressions. REALbasic doesn’t have a direct equivalent, but it does have RBScript which allows you to write and run your own code within your REALbasic application. With careful design, we can build our own implementation of Eval using RBScript, so let’s get started.
First, let’s understand what Eval does. Essentially, it takes as input a string that contains an expression to evaluate. Usage is like this: result = Eval(expression). For our purposes, we can return the result as a Variant.
In REALbasic, we’ll want a subclass of RBScript, so create a new class, which we’ll call Evaluator, and set its super to RBScript. To this class, add a private property: mResult As Variant. We’ll use this value to return the result of the evaluation.
Now add a new public method called Eval with this code:
Function Eval(expression As String) Returns Variant
Dim source As String
source = "Dim expr As Variant = " + expression + EndOfLine + _
"Print(expr)"
Self.Source = source
Self.Run
Return mResult
End Function
This code creates a simple line of REALbasic code that will parse the expression and runs this code using RBScript. The result it output using the Print command which will call the Print event in the Evaluator class. Speaking of which, add this code to the Print event:
This will assign the value that was output with Print to the property we created so that we can return it.
That’s it. Our Eval function is now ready to use. To test it, create a Window with two EditFields (ExpressionField and ResultField) and a PushButton and add this code to the button’s Action event:
Dim result As Variant
Dim myEval As New Evaluator
result = myEval.Eval(ExpressionField.Text)
ResultField.Text = result.StringValue
Download Evaluator project