lua-users home
lua-l archive

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


Mark Hamburg wrote:

> The first thing I will assume is that you then have some form of shared
> lifetime management for these objects such as reference counting. Now,
> however, you have the issue that the Lua side links can go away before
> the object does which means that you need to be prepared for that to
> happen. This will show up in the form of the lookup in the fully-weak
> map from the C++ object to the Lua full userdata returning nil.
> Effectively, Lua has forgotten about the button and so the on_click
> isn't going anywhere.

Yes, this is exactly my problem.

> The easiest way to do this is to add logic to the code that increments
> and decrements the reference count to add the object to a set of
> preserved objects when the count transitions from 1 to 2 and remove it
> from this set when it transitions back.

Thanks a lot, it sounds like a solution. However, I don't like tracking
these transitions, so I came up with an idea of something like garbage
collection.

I could create a fully strong (sic!) table in the registry, let's call
it "objects table", and store there a map between C++ objects (as light
userdata) and their full userdatas (which will be guaranteed to be
unique per object). Callbacks can be stored in the userdata's env table.

Periodically, a "garbage collection" procedure is triggered. It
traverses the objects table. All objects in the table with reference
count equal to 1 are removed from the table.

When an object with reference count equal to 1 is pushed from Lua to C++
function, it is added back to the objects table.

-- Gregory Bonik