+2 votes
by (200 points)

Hi,

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 (68.6k 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.

 

...