0 votes

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?

in Engine by (570 points)

1 Answer

0 votes
Best answer

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 = []
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: https://godotengine.org/qa/19396/how-do-i-duplicate-a-dictionary-in-godot-3-0-alpha-2?show=19400#a19400

by (29,088 points)
selected by

Understood, thank you for your answer.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.