ExpressionEval Manage Variables

1. Description

You can use variables in expression, one or more without any limitation. The type and the content of the variable must be defined after the parse (variables are found) but before evaluate the expression.

When you input an expression, it could contains variables. In the example below, the expression contains two variables:

a=b

2. Parse and execute

The next stage consists to parse the expression (decode it), so the variables will be detected by the evaluator.

// decode the expression and found variables
ParseResult parseResult = evaluator.Parse("a=b");

3. Get variables

After the parse, it’s possible to get all variables defined in the expression:

 ExpressionEval evaluator = new ExpressionEval();

//--decode the expression
ParseResult parseResult = evaluator.Parse("a=b");

//--displays all variables used in the expression
int i = 0;
foreach (ExprVarUsed exprVar in parseResult.ListExprVarUsed)
{
  i++;
  Console.WriteLine("Var #" + i + ", Name=" + exprVar.Name);
}

The execution of this code displays two variables: ‘a’ and ‘b’ used in the expression.

Var #1, Name=a
Var #2, Name=b

4. Define variables type and value

The next step is to define these variables present in the expression: define the type and set a value. Variable can be a boolean, an integer, a string or a double. Four methods exists to do that:

evaluator.DefineVarBool("BoolVar", true);
evaluator.DefineVarInt("IntVar", 12);
evaluator.DefineVarString("StringVar", "hello");
evaluator.DefineVarDouble("DoubleVar", 12.34);

For example: ‘a’ and ‘b’ are both set as an integer type with this value: 12.

evaluator.DefineVarInt("a", 12);
evaluator.DefineVarInt("b", 12);

5. Execute (evaluate) expression

Then the last step is to evaluate (execute) the expression, the variables will be replaced by set values.

// evaluage the expression content
ExecResult execResult = evaluator.Exec();

// get the result and displays it, its a bool value
Console.WriteLine("Execution Result: " + execResult.ResultBool);

The result for this example is :

Execution Result: true

6. Clear all variable definitions

Variable are available for all expressions you evaluate starting from the definition. It’s possible to remove all variable definitions with this instruction:

evaluator.ClearAllVarDefinition();

7. Get variable definitions errors

You can get errors occuring when define variables, with this instruction:

List<ExprError> listErrors= evaluator.GetListErrorExprConfig();

Type of these errors are: wrong variable syntax. These errors don’t stop the execution/evaluation of expressions in comparison of others errors: license and parse troubles.