+2 votes
by (200 points)


I was attempting to make a script where I have an array and I set a new variable to it, so they are the same array. When I use the <<pluck>> macro to randomly remove and return an item from the new array. However, both the new and old arrays have the item removed. How can I keep the old array from being modified?

1 Answer

+2 votes
by (64.2k points)

When you assign any reference type—i.e. any object type—you assign a reference to the underlying object, you do not make a copy of said object.  If you want to make a copy of the old array, then you need to do that explicitly during then assignment to the new array variable.  There are several ways you may do that, here are examples of two.


Using SugarCube's built in clone() function:

<<set $newArray to clone($oldArray)>>

Note that clone() makes a deep copy of the object—i.e. if the array contains other objects, they will be cloned as well.


Using the native JavaScript Array.from() method:

<<set $newArray to Array.from($oldArray)>>

Note that Array.from() makes a shallow copy of the array—i.e. only the original array is copied, any reference types contained within are left as references to their original objects.


Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.