lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Zhao Han <hz@fiosoftware.com>于2018年9月4日周二 上午12:01写道:
What if the value is not a table? 
---
tab = {}
setmetatable(tab, {__mode = 'v'})

r = function() end
tab['key'] = r

r = nil
collectgarbage()

When ‘r' is collected, how could ‘tab’ know that?

Thanks.
/hz


You can use a sentry table like this :

sentry = setmetatable({}, { __mode = "kv" })
sentry[r] = setmetatable({}, { __gc = function() print "r is collected" end })

btw, Pay attention about weak keys, they would removed from weak table AFTER running their finalizers.