Appending altering the copy and original array

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

Hello,

I’m having a little bit of a hard time with arrays. I need to append()the copy of one list with another and keep the original list untouched, but whenever I use this function the original list has its value changed as well. Could someone explain to me what’s going on and how to fix it?

var _arr_one : Array = [1, 2, 3]

func _ready():
    var _arr_two = _arr_one
    _arr_two.append([3, 4, 5])
    print(_arr_two)
    print(_arr_one)

Result:

[1, 2, 3, [4, 5, 6]]
[1, 2, 3, [4, 5, 6]]

Expected:

[1, 2, 3, [4, 5, 6]]
[1, 2, 3]
:bust_in_silhouette: Reply From: denxi

So arrays and dictionaries are both actually objects. When you say:

a = [1,2,3]
b = a

What actually happens is that b becomes a reference to the array itself, not a copy of one. What you want to do is use duplicate(), like:

a = [1,2,3]
b = a.duplicate()

One thing to keep in mind is that duplicate(), by default, will not duplicate arrays inside of other arrays. So if you did something like:

a = [[1,2,3], [4,5,6]]
b = a.duplicate()
b.append(7)
print (a)
print(b)

you get

[[1,2,3], [4,5,6]]
[[1,2,3], [4,5,6], 7]

because only the outer array would get duplicated. In order to duplicate every single array or dictionary, all the way down, you need to run a.duplicate(true)

Here’s the docs on duplicate: Array — Godot Engine (3.1) documentation in English

:bust_in_silhouette: Reply From: jgodfrey

Looks like you’re just pointing a second variable to the same, original array. So “both” would have the same content as they’re technically the same array.

This should work…

var _arr_one : Array = [1, 2, 3]

func _ready():
	var _arr_two = _arr_one.duplicate()
	_arr_two.append([3, 4, 5])
	print(_arr_two)
	print(_arr_one)

Notice the call to duplicate. That creates a 2nd copy