Hello, I am using Sugarcube2.34 and I have this issue with automating “variable selection”.
I am not native english speaker, so apologies if I use some terms incorrectly.
I have this part in my code where I need to set a bunch of different variables depending on how many times a button was pressed.
Not in a way that: 1st press → $var1 = 1 // 5th press → $var1 = 5
But like: 1st press → $var1 = 1 // 5th press → $var5 = 1
So in theory, 100th press would execute the contents of the button but using $var100 without me having to set up switch with 100 different cases.
My initial idea was something like
<<set $pressCounter to 0>>
<<link "Button">>
<<set $pressCounter += 1>>
<<set $var$pressCounter to true>>
<</link>>
This obviously doesn’t work.
So in sum: Can I make a button, that will set different variables(1↔X) based on another variable(selector) without having to code each and every single possible option.
I hope this makes sense, sorry if it was answered somewhere her before, not really sure if there is even a proper term for this issue to search.
Thanks in advance!
1 Like
Hello!
Do this:
<<link "Button">>
<<set $pressCounter += 1>>
<<set variables()[ "var" + $pressCounter ] to true>>
<</link>>
Whenever you want to invoke a variable’s name through another variable, use the “variables()[ $foo ]” method.
Bye now!
1 Like
Holy crap it works!
Thank you so much dude, you saved me buttload of hassle
Would buy you a beer if I could.
Cheers!
1 Like
note: The variables()
function returns a reference to the State.variables
property, so you can save yourself the additional cost of calling a function by using that property directly.
<<set State.variables[ "var" + $pressCounter ] to true>>
2 Likes
What exactly is the advantage of: State.variables vs. variables() ?
From a technical point of view there is an addition cost associated with calling a function.
And if you look at the source code of the variables()
function you will see that all it does is return a reference to the Object contained in the State.variables
property.
So when you use variables()
instead of just State.variables
in your code, you’re paying the addition cost of calling a function to end up with the same result.
1 Like