Can't figure out for loop & array appends behaviour

Godot Version

4.3

Question

Hello there! I’ve been trying to make a script that generates a standard, 52-card deck, which creates four nested arrays within an array corresponding to the four card suits. The issue is, I am stuck on the for loop for a buffer variable which shuffles the cards around, after which it should append each shuffled result to the main array, but instead it only takes the last result.

The relevant code in question:

var data_deck_suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
var data_deck_cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]

var data_deck_buffer = []
var data_deck_current = []

func deck_create():
	for suit in data_deck_suits:
		data_deck_buffer.clear()
		data_deck_buffer.append(data_deck_cards)
		data_deck_buffer[0].shuffle()
		print(data_deck_buffer)
		data_deck_current.append(data_deck_buffer[0])

And the output:

[["Ace", "4", "King", "Jack", "7", "5", "9", "10", "8", "Queen", "6", "2", "3"]]
[["King", "Queen", "9", "3", "5", "2", "7", "4", "Jack", "Ace", "6", "8", "10"]]
[["6", "Jack", "Queen", "8", "5", "King", "7", "Ace", "10", "9", "4", "2", "3"]]
[["8", "2", "6", "4", "Jack", "Ace", "King", "3", "9", "5", "7", "10", "Queen"]]
[["8", "2", "6", "4", "Jack", "Ace", "King", "3", "9", "5", "7", "10", "Queen"], ["8", "2", "6", "4", "Jack", "Ace", "King", "3", "9", "5", "7", "10", "Queen"], ["8", "2", "6", "4", "Jack", "Ace", "King", "3", "9", "5", "7", "10", "Queen"], ["8", "2", "6", "4", "Jack", "Ace", "King", "3", "9", "5", "7", "10", "Queen"]]

What am I doing wrong in this scenario, and how to make it append not just the 4th result, but also the previous 3?

Edit: Lol, I didn’t know the core array functions in Godot yet. : P (I removed my silly question)

Arrays are always passed by reference, not value. You need to duplicate the Array in your last line, like that:

And @vanders

shuffle() and clear() functions are native to Array class.

1 Like

Haven’t noticed this in the documentation, somehow, but it worked like a charm! Thanks.

1 Like

Lol, thanks for the note on the array functions. I’ve been programming for years, and never ran into default functions with these names. :man_facepalming:

1 Like