lua-users home
lua-l archive

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



----- Original Message ----- From: "Peter Loveday" <peter@loveday.org>
To: "Lua list" <lua@bazar2.conectiva.com.br>
Sent: Saturday, August 15, 2009 1:45 AM
Subject: Re: how does GC work with complex expressions using metamethods?


Sorry, my terminology wasn't clear. When the user does A:delete(), the delete method calls a CFunction with self.Cptr which allows the C++ object to get deleted.

Ack. This really should be done with a __gc metamethod on the usedata object. How do you know if any other references to the same C object exist or not (aside from assumed implementation conventions)? Allowing a hanging C ptr that has been deleted explicitly is asking for trouble.

No, that can't happen. Our C code registers each such pointer allocation and automatically deletes it later, regardless of whether there was one or multiple references in the lua script. But using metamethods like __add in expressions opens the new issue of intermediate C++ objects not being deleted until our C code gets around to it. We set it up this way many years ago because we couldn't figure out how to get the C++ object deleted automatically by the lua code. I know that was a bit of a hack but it was the best we could come up with at the time.


Then delete() sets self = nil and I leave the rest to the  lua GC.

This isn't really useful.. setting self to nil won't cause the table to be cleaned up. Keep in mind 'self' is merely one reference to the table; any caller references will need to be cleaned up too.


No, setting self = nil isn't done to get the table cleaned up faster. It's for our use in the script.


That is to say, every call to delete would have to be followed by settting (all) references to nil:

A:delete()
A = nil

So my question comes down to how to automatically get the Cfunction called with the object pointer so the C++ object can be free'd?

Right, so what you need to do is set a metatable on the userdata object with __gc defined. When the table is collected, and the last reference to that userdata goes away, it will (at some undefined time) be called.


That's what I'm working on today, but the process isn't at all transparent to me yet.

Michael