tmedwards / sugarcube-2

SugarCube is a free (gratis and libre) story format for Twine/Twee.
https://www.motoslave.net/sugarcube/2/
BSD 2-Clause "Simplified" License
177 stars 41 forks source link

State.setVar() executes mid-parse when called from <<set>> or <<run>> #129

Closed Sophismata closed 2 years ago

Sophismata commented 3 years ago

Describe the bug. When a <<run>> or <<set>> macro is used with State.setVar() — e.g. to dynamically set a variable who's name is referred to by a second variable — both variables have their values changed.

To Reproduce: Example passage text displaying this behaviour:

<<set $foo to "$bar">>
<p>$$foo: "<<= $foo>>" (<<= typeof $foo>>)<br>
$$bar: <<= $bar>> (<<= typeof $bar>>)</p>
<<run State.setVar($foo, Math.PI)>>
<p>$$foo: "<<= $foo>>" (<<= typeof $foo>>)<br>
$$bar: <<= $bar>> (<<= typeof $bar>>)</p>

Expected behaviour. Executing <<run State.setVar($foo, Math.PI)>> should change the value of variable $bar to Math.PI. The value of variable $foo should not be changed.

$foo: "$bar" (string)
$bar: [undefined] (undefined)

$foo: "$bar" (string)
$bar: 3.141592653589793 (number)

Actual behaviour. Both $foo and $bar are changed. Additionally, $foo is not set to Math.PI, but the stringified outcome of Math.PI (as this is happening while the macro is being parsed).

$foo: "$bar" (string)
$bar: [undefined] (undefined)

$foo: "3.141592653589793" (string)
$bar: 3.141592653589793 (number)

Project details.

Desktop details.

Akjosch commented 3 years ago

I can't reproduce State.setVar() doing anything wrong, with SC 2.35.0. What I can reproduce is this line giving you the impression the value is wrong:

<p>$$foo: "<<= $foo>>" (<<= typeof $foo>>)<br>...</p>

What happens the first time this is run is that $foo evaluates to "$bar", and since the $bar variable doesn't exist yet this gets printed verbatim, as per the naked variable syntax. The second time around $bar exists, so its value gets printed instead.

Internal variables are still correct though, which can be checked via the console.

Sophismata commented 3 years ago

Thanks, that's good to hear. I'll check tonight & confirm — I'd thought the console reflected the results I'd seen but I could be mistaken.

tmedwards commented 3 years ago

@Sophismata Can this issue be closed?