Variable is edited when given in function argument

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

Hello everyone,

I don’t know exactly if my question is right, but here is my problem. I have the following piece of code, which is called from another node:

extends Node

var recursiveLoop_counter : int = 0

func updateChronology(tempoPriorities):
	var internPriorities = tempoPriorities
	var Priorities_order = []
	for i in internPriorities.size():
	recursiveLoop_counter = 0
	OrderPriorities(internPriorities, Priorities_order)

for i in range(1, min(internPriorities.size(), get_child_count())):
	get_node(str("ColorRect_NextTurn", i)).updateIcon(Priorities_order[i])
if internPriorities.size() < get_child_count():
	var empty_slots : int = get_child_count() - internPriorities.size()
	for i in empty_slots:

func OrderPriorities(intPriorities, Priorities_order):
	var Highest_priority: float = -1
	var ActiveCharacter: int = 0

for i in intPriorities.size():
	if intPriorities[i] > Highest_priority:
		Highest_priority = intPriorities[i] 
		ActiveCharacter = i

Priorities_order[recursiveLoop_counter] = ActiveCharacter

intPriorities[ActiveCharacter] = -1
if intPriorities.size()-recursiveLoop_counter > 0:
	OrderPriorities(intPriorities, Priorities_order)
	return Priorities_order

My problem is that it modifies the variable given in argument in the calling node.

For example, if in another node, I call it with this setup:

var ExampleArray = [5,4,1,2,8]
get_node(“Example”).updateChronology(ExampleArray )

Then ExampleArray will be returned = [-1,-1,-1,-1,-1], althought it shouldn’t change at all.
I’m convinced it’s something with the functions previously written, as I can’t reproduce it on simpler cases, but impossible to see where it hurts…

Here is a link to the simpler case I could make to show this : GitHub_link

Thank you in advance <3

:bust_in_silhouette: Reply From: kidscancode

Arrays are always passed by reference.

Also see here:

Built-in types are stack-allocated. They are passed as values. This means a copy is created on each assignment or when passing them as arguments to functions. The only exceptions are Arrays and Dictionaries, which are passed by reference so they are shared. (Pooled arrays such as PoolByteArray are still passed as values.)

Aaah ok thank you!
So I should use a duplicate(Array, true), right?

CaptainSweet | 2020-03-08 18:24

Array.duplicate() you mean. Your array is full of ints, so no need for the deep flag.

kidscancode | 2020-03-08 18:57

Ah yes, you’re right. Thank you a lot!

CaptainSweet | 2020-03-08 19:23