Using set function for Arrays

Hello! I’m using Godot 4.2,

I want to detect when an array changes so i used this hoping that it works the same way as other variables.

var selectedCards = Array():
		if selectedCards != newSelectedCards:
			print("Selected cards changed = ", newSelectedCards)
			if selectedCards < newSelectedCards:
			selectedCards = newSelectedCards

Turns out it doesn’t work because .append() doesn’t trigger the set function.
How can i work around this?

P.S. Pretty please explain to me in simple words i’m not very proficient with technical jargon.

Edit: I found this solution but i suppose it’s considered “janky”.

func _process(delta):
	selectedCardsSize = selectedCards.size()

var selectedCardsSize = 0:
		if selectedCardsSize != newSelectedCardsSize:
			print("Selected cards changed = ", newSelectedCardsSize)
			if selectedCardsSize < newSelectedCardsSize:
		selectedCardsSize = newSelectedCardsSize

If it works, then that’s all you need. But you might want something a bit more robust, that will still work when the game is paused.

I would create a custom class extending RefCounted, store the array in the class as a private variable (GDScript doesn’t have true private variables, but you can name it something like _my_array so you know not to access it directly). And then create a custom function for append() and any other manipulation and retrieval functions you need. Then have the class manipulate the array internally and emit a signal.

Objects are a lot slower than arrays, but unless you need to access it hundreds or more times per frame, it shouldn’t have a noticeable impact.

Alternatively, you can do the same thing without a custom class, and just a custom append function in the script the array is stored in. But it can be harder to be disciplined about not accessing it directly without something in the way.