Variable changes where it shouldn't

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

I tried to recreate a problem where a Matrix (Array inside Array) changes it’s values even though it shouldn’t.

For some reason after setting the tilemap, the Matrix empty cells changes it’s values to the same as the Matrix cells

extends Node2D

const WORLDSIZE = 5
onready var tilemap = $TileMap
var cells = []
var empty_cells = []
var timer = 0

func _ready():
print("Cells (should be random 1 and 0): ", cells)
print("Empty Cells (should be all 0): ", empty_cells) #this should still be a empty Matrix

func set_tilemap():
for x in cells.size():
	for y in cells.size(): 
		if cells[x][y] == 0:

func create_empty_matrix():
var empty_matrix = []
for x in WORLDSIZE:
	for y in WORLDSIZE:
		empty_matrix[x][y] = 0
cells = empty_matrix
empty_cells = empty_matrix
print("Cells (should be all 0): ", cells)
print("Empty Cells (should be all 0): ", empty_cells) 

func create_random_life():
for x in cells.size():
	for y in cells.size():
		if rand_range(0, 5) >= 3:
			cells[x][y] = 1
			cells[x][y] = 0

With my Limited understanding empty cells only gets called two times and no where am I assining it the same value as cells.
Am I turning mad? What am I doing wrong? Can someone replicate this?

:bust_in_silhouette: Reply From: jgodfrey

It looks like empty_matrix is defined as an empty array. Then, both cells and empty_cells are assigned the SAME array.

var empty_matrix = []
cells = empty_matrix
empty_cells = empty_matrix

Now, all 3 array references (the variables themselves) point to the same physical array. So, a change made to any of them will modify the single, underlying array and all will report the same contents when asked (because they are the SAME array).

If you want to create a second, independent copy of a given array, you need to use the duplicate() function of the Array class. Simply assigning one array to another (via =) just creates additional references to the same underlying array.

Thank you very much, that is it. Have to set deep copy true and it works.

empty_cells = empty_matrix.duplicate(true)
cells = empty_matrix.duplicate(true)

DuteNait | 2023-02-25 18:30