[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: how does GC work with complex expressions using metamethods?
- From: Javier Guerra <javier@...>
- Date: Fri, 14 Aug 2009 17:51:23 -0500
On Fri, Aug 14, 2009 at 5:37 PM, Michael
> 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?
> 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.
> Now what if I use an expression like the
> ÂÂÂ A = (B + C - D) / D - F*G ^ H
> There are a whole bunch of intermediate objects created as each operator is
> processed, but I can never get to them to delete them. When do they get
> garbage collected? Is it automatic, right after the expression is evaluated?
there's no reference to them, so yes, they'll be collected. but not
right after the expression, only when (if) there's memory pressure.
> That's the first question.
> Related to that is a second question.ÂThe class holds a pointer to a C++
> object. So, when the table (class) gets gc'd,Âit needs toÂdeleteÂthat C++
> object as well.
> I've gone back and forth in the blue book trying to understand this and I
> just don't get it from the discussion and the examples. I can see that
> *something* has to have a metamethod __gc which calls a Cfunction with
> userdata containing the C++ pointer. But the question is the linkage between
> all these things.ÂI just don't see what to do. Whenever lua tries to collect
> the table,ÂI want it to call a Cfunction with the pointer that should be
Lua tables don't call a __gc metamethod, only userdata objects do.
if you have a __gc method (and you should if you have a pointer to a C
object), you have to use userdata, not Lua tables. But, a table can't
hold C pointers, so you should be using userdatas anyway, right?