Array not being duplicated

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


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!

:bust_in_silhouette: Reply From: Bean_of_all_Beans

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