A weird problem with array.insert()

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

When using array.insert in this way it seems to work fine:

var a = 0
var examplearray =[]
func _ready():
    examplearray.insert(0, a)
    a += 1
    examplearray.insert(1,a)
    print(examplearray)

OUTPUT: [0,1]

But when using arrays inside arrays the output gets weird:

var a = [0,0]
var examplearray = []
func _ready():
    examplearray.insert(0, a)
    a[0] += 1
    examplearray.insert(1,a)
    print(examplearray)

OUTPUT: [[1,0],[1,0]]

and the output should be: [[0,0],[1,0]]

Can anyone explain why is this happening

:bust_in_silhouette: Reply From: HyperlinkYourHeart

Integers and other basic types are passed by value, so when you pass one to insert, it is the value that gets inserted into the array. If you change the value of the variable and pass it again, it is the new value that gets passed.

Arrays, dictionaries, and objects are passed by reference. As such, when you pass an array to insert, then update it, you are still updating the same array instance. When you pass it to insert again you are just passing another reference. The array you are inserting to contains two references to one array.

From the docs:

Built-in types are stack-allocated. They are passed as values. This
means a copy is created on each assignment or when passing them as
arguments to functions. The only exceptions are Arrays and
Dictionaries, which are passed by reference so they are shared.

Thanks! And in my case, to fix the problem i just needed to add to the array .duplicate()

Hmmm | 2023-06-28 14:33