Home
Categories
Dictionnary
Download
Project Details
Changes Log

Variables


    1  Variable types
    2  Usage
       2.1  Variables in expressions parsing
       2.2  Creating global variables
    3  Local variables
    4  Local constants
    5  Notes

It is possible to use variables in expressions. For example, the following expression: "a + 2", takes the value of the variable a and adds 2 to this variable.

Variable types

Variables can have the following types: Variables can have the following structure type:

Usage

Variables in expressions parsing

Variables are automatically detected in expressions[1] . For example, in the following expression:

      Equation equation = ExpressionJ.parse("a + 1");  

the equation contains one variable of name a. This means that the following code will work:
      Equation equation = ExpressionJ.parse("a + 1");  
      Map<String, Variable> vars = equation.getVariables();  
      // vars contains one variable with the name "a"  
      vars.get("a").setValue(2);  
      Object result = equation.eval();   
      // the result is 3       

Creating global variables

Main Article: using global variables

It is also possible to set variables directly. This allows to share the same variables between more than one expression. For example:

      List<Variable> varList = new ArrayList();  
      Variable var = new Variable("a", Expression.TYPE_INTEGER);  
      varList.add(var);  
  
      Equation equation = ExpressionJ.parse("a + 1", varList);  
           
      var.setValue(2);  
      Object result = equation.eval();   
      // the result is 3       

Local variables

Local variables are detected when an typed assignation is present in an expression. For example, in the following expressions, a is a local variable:

      Equation equation = ExpressionJ.parse("int a = 2; return a + 1;");  
      Equation equation2 = ExpressionJ.parse("var a = 2; return a + 2;");  

whereas in the following expression a is a global variable[2] :

      Equation equation = ExpressionJ.parse("a = 2; return a + 1;");  

Local constants

The const keyword allows to declare local constants which can not be modified after their creation. For example:

      Equation equation = ExpressionJ.parse("const a = 2; return a + 1");  
      Object result = equation.eval();   
      // the result is 3       

A local constant behave just like a variable, except that it can not be modified after it had been defined. For example, the following code is not allowed:

      const a = 2; a = a + 2; return a;        

Notes

  1. ^ In that case they have by default a dynamic type
  2. ^ See also Parsing an expression

Categories: concepts

Copyright 2018 Herve Girod. All Rights Reserved