Juliano
Juliano

Reputation: 463

Emit local variable values during Groovy Shell execution

Consider that we have the following Groovy script:

temp = a + b
temp * 10

Now, given that a and b are bound to the context with their respective values, and that the script is executed using a groovy shell script.

Is there a way I could obtain the value of thetemp variable assignment, without printing/logging the value to the console? For instance, given a=2 and b=3, I would like to not only know that the script returned 50 but also that temp=5. Is there a way to intercept every assignment to capture the values?

Any suggestions or alternatives are appreciated. Thanks in advance!

Upvotes: 1

Views: 271

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

You can capture all bindings and assignments from the script by passing a Binding instance to the GroovyShell object. Consider following example:

def binding = new Binding()
def shell = new GroovyShell(binding)

def script = '''
a = 2
b = 3
temp = a + b
temp * 10
'''

println shell.run(script, 'script.groovy', [])

println binding.variables

Running this script prints following two lines to the console:

50
[args:[], a:2, b:3, temp:5]

If you want to access the value of temp script variable you simply do:

binding.variables.temp

Upvotes: 1

Related Questions