lua-users home
lua-l archive

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

On Sat, Dec 31, 2011 at 9:32 AM, Patrick Rapin <> wrote:
>> How do I bind C++ classes to Lua so that when I try to convert a Lua
>> object to a C++ class, it succeeds even if the object contains a C++
>> class that's derived from the one I want?
> There are probably plenty of ways to do this. I don't know if major
> automatic binding libraries like Swig or toLua support this.
> What I can tell is how the custom binding of our Pipeline library works.
> Each Lua object is represented by a full userdata consisting of a
> pointer to the C++ object, and a string buffer to store the *class
> name*.
> There is also a shared table, used as a hash table, with the class
> names as keys and the base class names as values (or nil if the class
> does not derive from another one).
> Having that, Pipeline can check whether a given Lua object is
> compatible with the required argument class type.

Since I am rewriting dub [1] in Lua, this is a feature I would like to
add automatically. My idea, close to Patrick's is to add a "_S" field
in the full userdata's metatable with class names as keys and true as
values. What I want to do is that this only happens after normal
metatable comparison instead of throwing an error so that it does not
slow down bindings without this feature.

Of course, this will only work with the first base class in case of
multiple inheritance.

class A {};
class B {};

class C : public A, public B {};

We cannot cast a void* pointer to C back to B.

There is another idea that I am thinking of but I stumble on the fact
that it would require that the bindings are loaded in a particular

The idea is to use super class's metatable as the userdata's
metatable's metatable. Then we do not need to duplicate bindings in
every sub-class, we can use the metatable nesting to resolve method
functions and type casting. This is elegant and makes the binding code
for sub-classes lighter but makes methods calls in sub-classes slower
(1 more metatable to find method, 1 more metatable to type cast) so I
am not sure it is worth it.