Help with array updating variable

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By stevepetoskey

I have no idea if this is a bug or intended, but here is a sample code I wrote that shows what I am dealing with.

var array = []
var array2 = [1,2]
array = [array2,1]
array2[0] = 3
print(array)

It should print (or at least I want it to print): [[1,2],1]
But instead it prints: [[3,2],1]
Any help would be appreciated, thank you.

:bust_in_silhouette: Reply From: jgodfrey

Arrays are always passed by reference, so when you insert array2 into array via:

array = [array2, 1]

You’re not inserting a copy of array2, that’s just a reference to the one, single array2 instance.

So, when you update the first element of array2, that change is also reflected in array, since it just contains a reference to (the now changed) array2.

I’m not sure what you’re trying to do, but if you want to insert a copy of array2 into array, you can use the array’s duplicate() function`. See the docs here:

Thank you! The duplicate() function worked!

stevepetoskey | 2020-11-05 21:45

If it worked, you may select the answer so others can see that it solved your issue.

p7f | 2020-11-06 15:45