The Script class
The Solver and Solver$ classes provide methods to wrap up the whole process of parsing and evaluating an expression or algorithm. Although quick and easy there may come a time when you want to control this process tourself.
To take charge the first thing you need is a Script object. To create the object use -
Script script = new Script(code);
where code is one of the following types
- String,
- String array or an
- List of String(s)
Once created you can parse it with one of these -
script.parse(); // Basic mode
script.parse_(); // Expert mode
You can test to see if it has parsed successfully with -
script.isParsed();
Which returns true if no errors detected. Once parsed the script can be evaluated as many times as you like with -
script.evaluate(); // Basic mode
script.evaluate_(); // Expert mode
Parsing only needs to be repeated if the script's expression or algorithm changes, which can be done with -
script.setCode(code);
this method accepts the same parameter types as the constructor.
Every script object has its own 'data store' which holds information about variables used in the script. This store is cleared when parsed but not when evaluated. This means that once parsed you can initialise any variables used during evaluation.
The following code demonstrates this, back to Pythagorus -
String[] code = {
"hyp = sqrt(a^2 + b^2)",
"print('The hypotenuse of a right angled triangle with sides ')",
"println(a + ' and ' + b + ' is ' + hyp + EOL)"
};
// Create and parse the script
Script script = new Script(code);
script.parse();
script.storeVariable("a", 5);
script.storeVariable("b", 12);
script.evaluate();
script.storeVariable("a", 4);
script.storeVariable("b", 3);
script.evaluate();
script.storeVariable("a", 15);
script.storeVariable("b", 8);
script.evaluate();
When executed the output looks like this
The hypotenuse of a right angled triangle with sides 5 and 12 is 13.0
The hypotenuse of a right angled triangle with sides 4 and 3 is 5.0
The hypotenuse of a right angled triangle with sides 15 and 8 is 17.0
Some things to note,
- although the script was parsed once, it was evaluated it three times,
- each time the variables were initialised with different values,
- it is not possible to evaluate this script without initialising the variables (for instance immediately after parsing at line 8) because it would cause an 'attempt to use an uninitialised variable' error.
After evaluation it is also possible to retrieve variables used in the expression e.g.
float hypotenuse = script.getVariable("hyp").toFloat();
Using the Script class gives the user much more control over the whole process and also allows for data to be shared between the script and the application evaluating it.