Runtime evaluation: Difference between revisions

Line 63:
The last expression evaluated in the script, a list of years found, is the return value of the '''evaluate()''' method.
 
<br>'''Evaluation with variables'''<br><br>
There are several approaches to evaluating a script with variables:
*'''GString''' embedded values
Line 69:
*'''Eval''' shortcut
 
'''GString''' embedded values'''<br>
Setting up the script as a '''GString''' with embedded value parsing is a "natural" ''ad hoc'' solution for Groovy programmers, but there are possible pitfalls if the script itself contains '''GString'''s.
<lang groovy>def startYear = 2008
Line 84:
Notice that in the script the embedded value "${it}" must be ''quoted'' with backslash (\) to prevent parsing as a part of the script '''GString'''. However, it is still correctly parsed within the internal '''GString''' when the script is run.
 
'''Binding variables''' variables<br>
'''GroovyShell''' uses a '''Binding''' object to pass variable values to a script. This is the only way to pass variables if the script comes from a '''File''' or '''InputStream''', but even if the script is a string '''Binding''' avoids the nested quoting issue caused by the ''ad hoc'' use of '''GString'''.
<lang groovy>def context = new Binding()
Line 114:
println binding.yearList</lang>
 
'''Eval shortcut''' shortcut<br>
For simple evaluation of string-based scripts with only a few variables (like this one), the '''Eval''' class has static shortcut methods that do the '''Binding''' setup and '''GroovyShell''' evaluation under the surface. '''Eval.me(script)''' evaluates a script with no variables. '''Eval.x(x,script)''', '''Eval.xy(x,y,script)''', or '''Eval.xyz(x,y,z,script)''' each evaluates a script with 1, 2, or 3 variables, respectively. Here is an example with start and end years as script variables ''x'' and ''y''.
<lang groovy>def years5 = Eval.xy(2008, 2121, '''
Anonymous user