lua-users home
lua-l archive

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

Joey Mukherjee <> writes:
> 2) My C++ stuff is doing all its own memory management and sometimes I
> free stuff which then Lua tries to garbage collect.  At least that  is
> what I think is happening since I reuse my Lua state.  Is there a  way
> to tell Lua that I own it all?  When I debug into my code, I see  a
> check for "own" and the flag is set to false.  Is there a way to  force
> to true?

I'm not sure whether it applies to your situation, but I have two sorts
of objects:  "temporary" objects (the sort of thing you'd usually create
on the stack in C++, and pass via const&), and "permanent" objects, for
which I generally use reference-counting pseudo-pointers in C++ (my
class for that is "Ref<T>").

What I do in swig is let it manage memory for the "temporary" objects (I
don't want to bother and they're temporary anyway), and for permenant
objects, I _always_ let swig have a Ref<T> for the object, rather than
let it create the object.  So, for instance, I tell swig to never make
constructors, and make my own wrapper functions like:

  Ref<Obj> make_obj (...) { return new Obj (...); }

That way, Lua's GC will always do pretty much the right thing -- as long
as there's a Lua reference left, it will keep the Ref<Obj> around, which
means the reference count in the Obj will never go to zero.  When Lua's
GC collects it, then it will destroy the Ref<Obj>, releasing that
reference, and deleting the Obj if it's the last one, but _not_ deleting
it if there are still references to it in C++ land.


Dictionary, n.  A malevolent literary device for cramping the growth of
a language and making it hard and inelastic. This dictionary, however,
is a most useful work.