Follow up question/problem. Seems I am doing something wrong with dictionary manipulation?

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

On the same Note as the previous post, but a different problem. Here is the code again

extends Node

var grid := {}

var _cell_info := {
	"id": "",
	"walkable" : true,
	"move_cost" : 1,
	"unit" : null
}

func create_empty_grid(x_tiles: int, y_tiles: int) -> void:
	for x in range(0, x_tiles, 1):
		for y in range(0, y_tiles, 1):
			grid[str(x) + "," + str(y)] = _cell_info
			grid[str(x) + "," + str(y)].id = str(x) + "," + str(y)

func _ready():
	create_empty_grid(2,2)
	grid["0,0"].id = "0,0"
	print(grid["0,0"])
    print(grid["0,1"])
	grid["0,1"].id = "0,1"
	print(grid["0,0"])
	print(grid["0,1"])

I am now seeing that when I try to modify the values inside one key, I end up modifing all the values in all the keys. What I get as an output is this

{id:0,0, move_cost:1, unit:Null, walkable:True}
{id:0,0, move_cost:1, unit:Null, walkable:True}
{id:0,1, move_cost:1, unit:Null, walkable:True}
{id:0,1, move_cost:1, unit:Null, walkable:True}

So maybe I am doing something wrong with the dictionary manipulation. I dont think it has to do with the fact that each value gets its initial setup from the same var, but who knows at this point. Madness… (or lack of knowledge from my part)

:bust_in_silhouette: Reply From: cm

I believe the issue is with the following line:

grid[str(x) + "," + str(y)] = _cell_info

You are assigning the same _cell_info dictionary to each value in grid. To fix this try:

grid[str(x) + "," + str(y)] = _cell_info.duplicate()

Thanks for the awnser. It was, as expected, the same problem as my previous post.

Pomelo | 2022-06-02 18:52