Why is the dictionary not working? it's literally 3 am ,and i'm sitting over this problem for an hour!

I’m losing my mind, because i’m literally picking a value from the table and it returns me a nil,
even if i set a true value, right before picking the value and printing it, help!


image

1 Like

Apparently, GetCell(...).ToIterate doesn’t have those fields.

Saying ToIterate[X][Y] in the line before is unrelated, as that’s apparently a different. If you shared the whole code maybe it would be easier to help.

But i literally changed the index value above the same index value ,when printing it

local function GetCell(X,Y,Table)
	if Table[X] then
		return Table[X][Y]
	end
end
ToIterate[Coords.X][Coords.Y] = true
print(GetCell(Coords.X,Coords.Y,FreeCells),ToIterate[Coords.X][Coords.Y])

There’s only (possible thing that could make a bug) a metatable, but it doesn’t matter

	setmetatable(ToIterate,{
		__index = function()
			return {}
		end,
	})

Where are you getting the values for Coords.X and Coords.Y?

Coords.X and Coords.Y are an integers, that’s all you need to know.
But if you truly want to know, that’s the whole function.

local function InsertToFreeCells(Table)
		for n = 1,#Table do
			local Coords = Table[n].Coordinates
			if not GetCell(Coords.X,Coords.Y,ToIterate) and not GetCell(Coords.X,Coords.Y,Paths) then
				table.insert(FreeCells,Table[n])
				ToIterate[Coords.X][Coords.Y] = true
				print(GetCell(Coords.X,Coords.Y,FreeCells),ToIterate[Coords.X][Coords.Y])
				FreeCells.length += 1
			end
		end
		return true
	end

This is the bug.

Or part of it anyways.

Saying ToIterate[X], if X doesn’t exist as a member, will trigger your meta method and return a new table {}. Critically though, __index will not set ToIterate[X] = {}. It just returns and leaves it, so when you do

ToIterate[X][Y] = true
-- or, equivalently:
local x = ToIterate[X]
x[Y] = true

And the first lookup fails, your meta table takes over so you end up doing

local x = {} -- because ToIterate[X] failed so __index returns this
x[Y] = true

And then when you print out ToIterate[X][Y], the lookup fails again (because __index doesn’t modify the table unless you tell it to) and tries to lookup Y on a new empty table.

All that’s to say that you probably want your metatable to do this:

__index = function(t, k)
  local new = {}
  rawset(t, k, new) -- t[k] = new but withou invoking this meta method again
  return new
end)
1 Like