lua-users home
lua-l archive

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



----- Original Message ----- From: "Javier Guerra" <javier@guerrag.com>
To: "Lua list" <lua@bazar2.conectiva.com.br>
Sent: Friday, August 14, 2009 3:51 PM
Subject: Re: how does GC work with complex expressions using metamethods?


On Fri, Aug 14, 2009 at 5:37 PM, Michael
Newberry<mnewberry@mirametrics.com> wrote:
> I wonder if anyone can help me with the following questions. I am trying > to > add metamethods like _add and __mul to a lua class (a table configured > in
> the appropriate way).

so your objects are not userdatas, right? just tables with metatables?


Right, my classes are tables, declared generally like this:

   CData = { Cptr = nil }

   function CData:new()
     local o = {}
     setmetatable(o,self)
     self.__index = self
     o.Cptr = CreateData()
     return o
   end

When the user uses A = CData:new() the registered function "CreateData" is called and it creates the C++ object aand returns a pointer to it. Class methods use o.Cptr to talk to the C++ object.


> Each of these arithmetic metamethods must return a new
> object. For example, suppose B and C are objects and I use
>
> A = B + C
>
> The result A is a new object, which is fine. I can delete A and grab its
> memory whenever I want to.

no, you can't _delete_ an object, you just remove any reference to it,
and the GC will eventually collect it.

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. Then delete() sets self = nil and I leave the rest to the lua GC.

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?

Michael