Runtime evaluation: Difference between revisions

m
m (→‎{{header|Groovy}}: (Shorten contents))
Line 71:
*'''Eval''' shortcut
 
'''gstringGString 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 86:
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.
 
'''bindingBinding 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 116:
println binding.yearList</lang>
 
'''evalEval 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