I think by the time you call the print function, the x and y are re-set in the script itself - it can't work the way you want it to. How about sth like this:
//x = 'Hola'
//y = 'Mundo'
def setDefsIfNeeded(Map defs) {
defs.each { key, value ->
if (!binding.variables.containsKey(key)) {
binding[key] = value
}
}
}
setDefsIfNeeded x: 'Hello', y: 'World'
println "$x, $y!"
This will print out 'Hello, World!' as the binding is clean. Now, uncomment the first lines to simulate the binding being pre-set before calling the script, and you will see 'Hola, Mundo!'.
I agree it is not beautiful, but I don't know any other way of doing that. You could name the method better, or even hide the I don't know the full context. You can also do this:
//x = 'Hola'
//y = 'Mundo'
setDefs = { Map defs ->
defs.each { key, value ->
if (!binding.variables.containsKey(key)) {
binding[key] = value
}
}
}
setDefs x: 'Hello', y: 'World'
println "$x, $y!"
and actually set the setDefs closure to the binding, so that it is not defined in each script.
These are just some of my ideas, maybe others will be able to come up with sth better.
Wujek