lua-users home
lua-l archive

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


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?

> 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
> following?
>
>     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
> deleted.

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?



-- 
Javier