.clear resets array before .append can append it

Godot Version

v4.6.2.stable.official [71f334935]

Question

I have the following _ready function:

func _ready() β†’ void:
    all_cells = get_used_cells()
    all_cells.sort_custom(array_sort)
    for i in range(len(all_cells)):
	    j = all_cells[i]
	    if i == 0:
		    print(j)
	    if j.y == all_cells[i-1].y:
		    print("^ same as v")
		    print(j)
		    current_row.append(j)
		    #print(current_row)
	    elif j.y >= all_cells[i-1].y:
		    print(current_row)
		    all_rows.append(current_row)
		    current_row.clear()
		    #print(j)
    print(all_rows)


func array_sort(a: Vector2i,b: Vector2i):
	if a.y == b.y:
		return a.x < b.x
	return a.y < b.y

My problem now is that β€œcurrent_row.clear()” clears the array before the previous line finishes and it then just prints an empty array. Is that supposed to be this way? And if yes, how can i work around it?

Arrays are always passed by reference.
all_rows.append(current_row) adds a reference to the current_row array into the all_rows array. When the current_row array gets cleared, the reference in all_rows still points to the same (but now empty) array.

If you intent to clear the array but keep the data in the other array, you have to duplicate it:

		   all_rows.append(current_row.duplicate())

thanks, that works for me