lua-users home
lua-l archive

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



----- Original Message ----- From: "Sam Roberts" <vieuxtech@gmail.com>
To: "Lua list" <lua@bazar2.conectiva.com.br>
Sent: Friday, August 14, 2009 4:29 PM
Subject: Re: how does GC work with complex expressions using metamethods?


On Fri, Aug 14, 2009 at 4:06 PM, Michael
Newberry<mnewberry@mirametrics.com> wrote:
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.

This isn't going to work.


Maybe I'm not understanding what you are saying here, but what I described has worked for years. But it requires the user call CData:delete(). So it isn't automatic. Is it "not being automatic" that you mean isn't going to work? If so, yes, that is the problem.

CreateData needs to return a (full) userdata. That userdata will
probably contain nothing but your c++ pointer, and must have a
metatable, with a __gc function that will delete that pointer.


I already tried to do that, but maybe I goofed something. Here was the code inside the Cfunction CreateData():

   // ... create the C++ object with pointer pData

   CData** ptr = (CData**)lua_newuserdata( L, sizeof(CData*) );
   *ptr = pData;
   return 1;

Back in the lua new() method, the value of self.Cptr has "something". But what is that something? And how do I attach a __gc metamethod to it?

Michael

I can think of ways of getting around this, but they are unstable
hacks, and besides, userdata was designed to do exactly what you are
doing: encapsulate a C/C++ object/pointer, and give you hooks into
garbage collection so you can manage their lifecycle.

Cheers,
Sam