Lua垃圾回收


强引用和弱引用

关于弱引用:

https://www.lua.org/pil/17.html

官方的解释很好理解,弱引用就是不会阻挡GC的引用

那为什么需要这样的功能呢?

Nevertheless, sometimes even the smarter collector needs your help. No garbage collector allows you to forget all worries about memory management.
Similarly, any object stored in a global variable is not garbage for Lua, even if your program will never use it again.
a = {}
b = {}
setmetatable(a, b)
b.__mode = "k"         -- now `a' has weak keys
key = {}               -- creates first key
a[key] = 1
-- 在这一步,key指向了新的内存位置,原来的key不会再继续保持占用了
key = {}               -- creates second key
a[key] = 2
collectgarbage()       -- forces a garbage collection cycle
for k, v in pairs(a) do print(v) end