lua-users home
lua-l archive

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


Thanks. That’s what I needed. 

With a little improvement:

sentry[r] = setmetatable({val = r}, { __gc = function(o) print(o.val, 'is gc-ed') end})

Best Regards,
/hz 

在 2018年9月4日,上午2:55,云风 Cloud Wu <cloudwu@gmail.com> 写道:

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.