This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes


Can someone please help me understand why the below isn't doing a deep copy of the array and instead 'orig_text' still ends up being a reference to 'choices'?

orig_text = choices.duplicate(true)

print (orig_text[0].text)
print (choices[0].text)

func _on_Timer_timeout():
    if highlighted == 1:
        if choices[0].text == "":
            choices[0].text = "> " + choices[0].text

            print (orig_text[0].text)
            print (choices[0].text)

The first print statements confirm the duplication is done, but the print statements in the timer_timeout both end up printing the changed value. Not sure what I'm doing wrong here.

Any help with this is much appreciated!

Godot version 3.2.3.stable.official
in Engine by (53 points)

1 Answer

+1 vote
Best answer

I looked at the documentation for Array.copy, and I saw this:

If deep is true, a deep copy is performed: all nested arrays and dictionaries are duplicated and will not be shared with the original array. If false, a shallow copy is made and references to the original nested arrays and dictionaries are kept, so that modifying a sub-array or dictionary in the copy will also impact those referenced in the source array.

It seems that calling Array.copy(true) will only produce duplicates of any nested arrays and dictionaries, not objects. What is happening in your code is that you truly did duplicate choices into orig_text, but all the items in orig_text still point to the same locations as the items in choices. If you want to have a copy of the original items, you should call choices[i].duplicate(), where i is the index of the item. All nodes have a duplicate method which will return a copy.
This should work for your case.

Here is a small snippet I just thought up (I haven't tested it to see if it works; though it should):

var orig_text = []
for i in range(choices.size()):

Hopefully this helps

by (347 points)
selected by
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.