[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Finalisation of userdata in weak-valued tables
- From: Joshua Phillips <jp.sittingduck@...>
- Date: Fri, 31 Dec 2010 15:15:06 +0000
Hello.
A weak-valued table can be useful for caching objects, but having them
removed from the cache when they're no longer referenced.
I have been using a weak-valued table for this purpose. I have a data
structure like this:
cache = setmetatable({
[key] = {proxy = <userdata with __gc metamethod>}
})
When I want the object, I look in the cache table, and if it's not
there, recreate it.
Under some conditions, I find the object (the table containing the
userdata) in the cache, and store a reference to it in a local variable.
Then later, while I've still got the reference in the local variable,
the __gc metamethod of the userdata gets called.
I confirmed that the reference was still present in the local variable,
by searching locals with debug.getlocal.
This situation arises in both Lua 5.1.4 and Lua 5.2.0-alpha. Is this
normal?
I suspect that the GC decides at some point that the proxy is no longer
reachable through strong references (a correct decision), but delays the
call of the finaliser until later.
I'd provide a test-case, but due to the unpredictable nature of garbage
collection, it's rather difficult to reduce the code to test-case size.
(Any change in allocation patterns can result in this behaviour not
emerging.)
I'd like to know if this is expected behaviour, because if it is, I can
work with it.
Thanks.