Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

[Sugarcube] Pushing elements to an array

Using Sugarcube in Twine 2, I can't seem to get my arrays working right. I'm not sure if my problem is how I'm adding elements to the array or how I'm checking how many elements are in the array. I'll post all the relevant code.

Initializing the array:
<<set $magsRead = []>>

Checking the size of the array:
<<if $magsRead.length < 3>>

Adding elements to the array (I've tried both lines):
<<set $magsRead += ["Cosmo"]>>
<<set $magsRead += "Cosmo">>

The problem is that my array size check is never evaluating to true, even when activating the <<set>> macro 3 or more times. $magsRead.contains() does correctly determine if an added string is in the array. When I do <<print $magsRead>>, it prints every element that's been added one after another, with no delimiters, as if it thinks the whole thing is a string, not an array.

Is my only option here JavaScript? That seems like such a clunky answer to a problem that will likely only appear in one small part of the game. Plus, I'd find it odd if Sugarcube lets you create arrays but never modify them.

Comments

  • Use the push function to add an item to your array:
    <<set $magsRead to []>>
    <<set $magsRead.push("Cosmo")>>
    <<set $magsRead.push("Some Value")>>
    <<print $magsRead>>
    <<print $magsRead.length>>
    
    I don't believe SugarCube overloads operators like += to work with arrays.
  • Ah, that solved it. I did try using the push function after posting the question since I knew it existed in JavaScript, but I didn't wrap it in a <<set>> macro. Thanks!
Sign In or Register to comment.