Why and when should you actually use weak tables?

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

So some days ago i decided i wanted to learn weak tables. My only problem is that i cant really see any use for them?

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

Whats their use? i know that you use __mode to make a tables keys/values weak. But why would i even need to do that when i could just set them to nil?. Any help explainin an ACTUAL use case for them would be pretty cool because im hella confused why theyre so “useful”.

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

Yes. ive done some research but i sitll dont understand why you would use them inside your code. They just seem like a more advanced way of setting keys to nil/removing values

Again. Like i said anyone who can explain an actual use case for them inside a game would be really helfpul and cool :slight_smile:!

1 Like

One example is keeping track of instantiated objects when doing OOP:

local MyClass = {}
local instances = {}

function MyClass.new()
    local self = setmetatable({}, MyClass)
    table.insert(instances, self)
    return self
end

function MyClass:Destroy()
    table.remove(instances, table.find(instances, self))
end

This forces the consumer of MyClass to remember to call Destroy on every instance they create. That’s a valid approach, but normally when programming Lua, due to automatic memory management / GC, you don’t have to remember that so it goes against common practice. Making instances weak on values fixes this and is more convenient for the consumer.

Section 17 of PiL has some more examples: Programming in Lua (first edition)

1 Like