0 votes

If I define an array as equal to another array, then any function I use on the second array, also affects the first one. Example:

var real_array = [1, 2, 3]

func ready():
var temp
array = realarray
temp
array.remove(0)
print(real_array) ---> print [2, 3]

Now I found the duplicate() function while writing this and it makes me think that this might not be a bug after all, but it does seem like odd behavior since other types of variables don't function like this (at least the ones I've tested).

in Engine by (55 points)

I think this should be an issue on GitHub.

1 Answer

0 votes

The assignment only copies a reference to the original structure. This is also true for all objects and dictionaries and is by design. Use the duplicate() method to assign a duplicate of the array.

https://docs.godotengine.org/en/3.1/classes/class_array.html

by (3,248 points)

Fair enough. Though I can't see why it would ever be useful. But yea had figured out duplicate() was an option.

This is quite common, also in other languages (i.e. JavaScript). Normally, copying complex data structures can take quite a bit of time (& sometimes memory) so the default behaviour for all complex datatypes is just assigning by reference.

Fair enough. Thanks for the info.

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 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 webmaster@godotengine.org with your username.