lua-users home
lua-l archive

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


Hi list,
 
I was trying to convert a friend to Lua, but he is very concerned about safety issues. Especially concerning validity of types and data. And he made me find something looking like a hole in Lua garbage collection.
 
Let assume that I have a userdata created with my C function create, and that the finalizer of that user data (its __gc metamethod) is the global Lua function finalizer :
 
local foo,bar
 
function finalizer(self)
    print("finalized")
    bar = self
end
 
foo = create()
print(foo)
> userdata: 00580390
foo = nil
collectgarbage("collect")
collectgarbage("collect")
> finalized
print(foo)
> nil
print(bar)
> userdata: 00580390
bar = nil
collectgarbage("collect")
collectgarbage("collect")
> <no finalizer called>
 
So the problem is that once my finalizer is called it's never called again, but I still have references to the object. Is that normal ? Since after the finalizer call I have access to my object in the global scope, what prevents me from calling methods on it ? In fact I've tested it with a slightly more complex object, and methods get passed an invalid object. Methods that will misbehave if I don't detect myself if the object I'm getting has already been finalized or not.
 
I don't mind getting an answer like "storing references to an object in its finalizer is forbidden", provided it's official (like explicitly stated in the manual). But even in that cases it sounds a bit scary (fortunately it's not possible to reproduce the case with pure lua).
 
Jérôme.