Weak metatables not working?

I’m trying to set up a metatable with weak key references, but for some reason, it’s not working as it did before?

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

local reference = {}
weakTable[reference] = "hi"

print(weakTable) -- {[Table(CA5DF4CB4152A33E)] = "hi"}
reference = nil
print(weakTable) -- should print "{}" but prints {[Table(CA5DF4CB4152A33E)] = "hi"}

Am I misremembering how weak metatables are handled? Is this a bug?
Thanks for reading :slight_smile:

2 Likes

Immediate GC after reference clearing is not guaranteed or likely. For your test, try waiting a few seconds and/or “forcing” a GC by allocating and deallocating a bunch of memory.

2 Likes

Why not use table.clear(reference) instead of reference= nil?

1 Like

This would free memory inside the reference table itself. Setting the entire variable to nil clears the handle to the variable which enables garbage collection to clean up the entire table, not just what’s inside it.

Though I will note, iirc, table.clear does not deallocate slot memory in the table. It will only remove filled slots and potentially mark the data for those for GC. For example, calling it on a table with 10 things in it will cause the table to appear empty but in memory the table will still have whatever bytes size it was.

2 Likes

i tried yielding the thread, but it didn’t work. previously it would’ve gotten rid of the key immediately.

That’s just “lucky”. There is no guarantee when the garbage collector will run and cleanup memory. You can’t do one test and assume the same behavior will happen each time, even if it was somewhat consistent.

1 Like

i see. i thought garbage collection runs at the end of each cycle, but really there’s no documentation on the luau page that says that.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.