Sugercube, is it possible to parse a Variables Value into Set Marco?

Twine Version: 2.6.1.0
SugerCube: 2.36.1

I have a widget, “skillxp” that will always take 2 Arguments like following:
<<skillxp $Strength 2>>

My question is if I already have _args[0] == $Strength, how can I parse its Value into a Set Marco
as <<set _args[0] += _args[1]>> will only overwrite _Args[0] to be 2, what I wish to achieve is:
<<set $strength += 2>>

Normal I would do this by a Switch statement like:

<<Switch _args[0]>>
  <<case $Strength>>
      <<set $Strength += 2>>
  <<case $Dexterity>>
      <<set $Dexterity += 2>>
  ...and so on...
<</swtch>>

Is there a more efficient way to achieve this?

Thank you for Reading!

(note: when I tested this, it did not work with _args, but did work with $args. This may be because I’m using an older version of Sugarcube (2.34))

You can use the State.variables object to access your variable. If $args[0] is “Strength”, then State.variables[$args[0]] will access $Strength.

So, with the following widget

<<widget "skillxp">>
<<set State.variables[$args[0]] += $args[1]>>
<</widget>>

you can use <<skillxp Strength 2>> to increase $Strength by 2.

2 Likes

Thank you very much for your timely reply!
I wonder how I have overseen this part of the Docs, very hidden to be honest.

I also upgraded recently here its mentioned in the Documentation
SugerCube Offical Documentation (Widgets)
Docs:

  • v2.36.0: Added the container keyword, _args variable, and _contents variable. Deprecated the $args variable in favor of _args.
1 Like

I went looking for the answer to this same question a few weeks ago and all I found was the suggestion to use the “Stupid Print Trick” to do it, so I was like “well, forget that, then.” I’m very glad to know there’s a more elegant alternative!

2 Likes

The State.getVar() and State.setVar() functions are what SugarCube uses itself within the code of macros like <<textbox>> that take a String Representation of a variable name ("$strength") as their receiverName argument.

<<widget "skillxp">>
    /* Assuming $args[0] equals something like "$Strength", and both $Strength & $args[1] contain numbers... */
    <<run State.setVar($args[0], State.getVar($args[0]) + $args[1]) >>
<</widget>>
3 Likes