Metatable __mode not working as expected

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

  2. What is the issue? Include screenshots / videos if possible!

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

local weakTable = setmetatable({}, { __mode = "k" })

local function createObject(name)
	return { name = name }
end


local obj1 = createObject("Objeto 1")
local obj2 = createObject("Objeto 2")


weakTable[obj1] = "Este é o objeto 1"
weakTable[obj2] = "Este é o objeto 2"


obj1 = nil

for k, v in pairs(weakTable) do
	print(k, v)
end

I wonder if the __mode metatable has been disabled in Roblox Studio.

I think you need to wait for the garbage collector to run. Try adding a wait() to your code before you print the table out.

1 Like

As said above, you need to wait until the next gc cycle

local weakTable = setmetatable({}, { __mode = "k" })

local function createObject(name)
	return { name = name }
end


local obj1 = createObject("Objeto 1")
local obj2 = createObject("Objeto 2")


weakTable[obj1] = "Este é o objeto 1"
weakTable[obj2] = "Este é o objeto 2"


obj1 = nil

local n = 0

while true do
	n = 0
	
	for _ in weakTable do
		n += 1
	end
	
	if n >= 2 then
		task.wait()
	else
		break
	end
end

print('gc finished', weakTable) -- ok