lua-users home
lua-l archive

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


On 15/01/2013 4:34 PM, William Ahern wrote:
>In C/C++ wrap/intercept the allocator so that there is a
>TrackedLuaCPointerNode* stored just before the allocated C/C++ memory
>region. This pointer is used as the head of a linked list of
>TrackedLuaCPointerNodes that point to the region.
Yeah, but these schemes are usually a bad idea. Scratch that--they're
_always_  bad. It's far saner to just suck it up and add reference counting
semantics to those C or C++ objects bound as userdata in Lua.

That should be even easier in C++ than in C, although I'm not too familiar
with C++. I would imagine that something like shared_ptr would be a sane
prerequisite for an automatic C++ bindings generator.

In any event, the process of adding reference counting--examining and
analyzing object lifetimes--would undoubtedly improve the quality of the
codebase generally.

I would question whether adopting reference counting everywhere would "improve the quality of the codebase generally." I do agree that adopting a disciplined set of resource management policies is critical. Reference counting is one of the tools available.

One reason I like C/C++ (compared to GC languages) is that I am in full control of object lifetimes. This makes things predicatble. Often the unique ownership pattern (eg. std::unique_ptr) is enough, and means that you don't need reference counting (and the associated overhead). Don't get me wrong, I do selectively use reference counting, but only when the object lifetime/usage patterns require it.

Also, extensive use of RAII in C++ means that deterministic destruction is required for correct operation in many cases.

In the case of Lua bindings we have a mismatch between managed lifetime semantics (a lot of C++ code) and non-deterministic finalisation (Lua GC). You're proposal is to always put Lua in control of object lifetimes.

One way to think about it is that we're talking about is "how do we implement safe weak-references to C/C++ objects from Lua?"

Whether a Lua binding should use weak references is certainly up for discussion. But when it is needed (and I assert that it is, sometimes) then it would be good to know what the available options are.

There seem to be two main approaches we've considered:

- Use a memory-block version counter so that Lua can poll for object validity. - Hook object deletion or destruction to invalidate the "weak references" (stored in a hash table or linked structure).

The version counter is efficient and elegant, but not failsafe unless you can ensure that: (a) the memory is never unmapped, and (b) the version counter field is never overwritten (consider larger reallocations after heap coalescing).

Ross.