Howdy, Stranger!

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

How do I copy an array in Sugarcube 2?

(I'm using Sugarcube 2 in Twine2)
I've setup the array $opponent and want to copy it to a temporary variable that I can manipulate without changing the source variable.

I tried this:
<<set $opponent to [1,2,3,4]>>
<<set $templist to $opponent>>

But if I then use the splice-function I also change $opponent as in:
<<set $templist.splice($templist.indexOf(4),1)>>
<<print $opponent>> --> 1,2,3

But if I use: <<set $templist to []+$opponent>> this happens with the random()-function:
<<print $templist.random()>> --> ,

So how do I copy an array with only the numbers and not the commas?
Thank you.


  • edited January 2016
    Traditionally, you'd probably want to call the <Array>.slice() method on $opponent:
    <<set $templist to $opponent.slice(0)>>
    However, you now also have the option of passing $opponent to the Array.from() static method:
    <<set $templist to Array.from($opponent)>>

    Either one will assign a shallow copy of $opponent to $templist.

    EDIT: Also, you do not concatenate arrays via the + operator. You would use the <Array>.concat() method. For example (and yes, this is yet another way to copy $opponent):
    <<set $templist to [].concat($opponent)>>
Sign In or Register to comment.