Runtime evaluation: Difference between revisions

m
→‎{{header|Groovy}}: (Shorten contents)
m (→‎{{header|Groovy}}: (Shorten contents))
Line 51:
<pre>[2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]</pre>
 
==='''Simple evaluation==='''<br><br>
The '''GroovyShell''' class allows the evaluation of a string or of the text contents of a '''File''' or '''InputStream''' as a ''Groovy script''. A script is a either a set of statements to be executed in order, or a Groovy class with a '''main()''' method, or a Groovy '''Thread''' subclass or '''Runnable''' implementation. The return value is the value of the last statement executed, or the value of an explicit '''return''' statement (if any).
 
Line 65:
The last expression evaluated in the script, a list of years found, is the return value of the '''evaluate()''' method.
 
==='''Evaluation with variables==='''<br><br>
There are several approaches to evaluating a script with variables:
*'''GString''' embedded values
Line 71:
*'''Eval''' shortcut
 
====GString'''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 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.
 
====Binding'''binding 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>
 
====Eval'''eval 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