Using variables in an embedded Groovy script

2023-09-25 Thread Jochen Wiedmann
Hi,

can anyone advise me, what is wrong with the following code: I'd
expect it to write out the word "Okay". Instead, it throws the
exception "Unexpected result: Hello, !"

final String scriptStr = "return \"Hello, $name!\";";
final GroovyShell gs = new GroovyShell();
final Script script = gs.parse(new StringReader(scriptStr));

final Binding binding = new Binding();
binding.setProperty("name", "world");
script.setBinding(binding);

final GStringImpl gsi = (GStringImpl) script.run();
final String[] gsArray = gsi.getStrings();
final String result;

if (gsArray == null || gsArray.length == 0) {
result = null;
} else {
result = String.join("", gsArray);
}

if (!"Hello, world!".equals(result)) {
throw new IllegalStateException("Unexpected result: " + result);
}
System.out.println("Okay.");



-- 
The woman was born in a full-blown thunderstorm. She probably told it
to be quiet. It probably did. (Robert Jordan, Winter's heart)


Re: Using variables in an embedded Groovy script

2023-09-25 Thread Paul King
You'd need to interleave the values from the GString.

On Tue, Sep 26, 2023 at 12:43 AM Jochen Wiedmann
 wrote:
>
> Hi,
>
> can anyone advise me, what is wrong with the following code: I'd
> expect it to write out the word "Okay". Instead, it throws the
> exception "Unexpected result: Hello, !"
>
> final String scriptStr = "return \"Hello, $name!\";";
> final GroovyShell gs = new GroovyShell();
> final Script script = gs.parse(new StringReader(scriptStr));
>
> final Binding binding = new Binding();
> binding.setProperty("name", "world");
> script.setBinding(binding);
>
> final GStringImpl gsi = (GStringImpl) script.run();
> final String[] gsArray = gsi.getStrings();
> final String result;
>
> if (gsArray == null || gsArray.length == 0) {
> result = null;
> } else {
> result = String.join("", gsArray);
> }
>
> if (!"Hello, world!".equals(result)) {
> throw new IllegalStateException("Unexpected result: " + result);
> }
> System.out.println("Okay.");
>
>
>
> --
> The woman was born in a full-blown thunderstorm. She probably told it
> to be quiet. It probably did. (Robert Jordan, Winter's heart)