Possible bug in 3.0 beta 1?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By DodoIta
:warning: Old Version Published before Godot 3 was released.

Basically I’m trying to save the value of an array A on another variable B (the variable’s names are just for example).

# A initialized elsewhere as an array
var B = A # executed once

I do that because A will be modified during the execution and I want to store its initial value for other purposes.

What happens is that B gets modified alongside with A; I’ve done my testings and I’m absolutely sure I store the value of A once, so B is not modified within my code.
I tried casting A’s value in a String value C and it worked: C is not updated with A.

var C = String(A) # works

Is this a bug of am I missing something about GDScript? Perhaps declaring var A = [] means that A actually stores a pointer to the array’s location? That would explain it, because the only thing that updates is the array stored in a memory location.
Anyway, can a person more experienced than me confirm this?

:bust_in_silhouette: Reply From: Zylann

Arrays and dictionaries are reference types, storing them in a different variable will not create a new copy, it will store yet another reference to it.

If you want to copy the array to preserve its initial values, you can do this:

B = []
B.resize(len(A))
for i in range(len(A)):
	B[i] = A[i]

If your array itself contains other arrays or dictionaries, you can use a deep_copy function I wrote a while ago that will copy everything recursively: How do I duplicate a dictionary in godot 3.0 alpha 2. - Archive - Godot Forum

Understood, thank you for your answer.

DodoIta | 2017-12-10 10:31