Question

I'm using Luabind to bind a C++ API to Lua. I have some objects that cannot be created directly, but rather must be created on another thread. I'm currently handling this by defining a "static" member called create that yields until the object is created:

luabind::class_<Foo>("Foo")
  .scope
  [
    luabind::def("create", &someCreateMethod, luabind::yield)
  ]

This works, but has the disadvantage of complicating the client API. For these classes, you cannot create them normally (e.g. local f = Foo()), but instead need to do local f = Foo.create().

Is it possible to define a Luabind constructor that doesn't actually call the C++ constructor, but instead another function that returns the constructed object (and can yield in the meantime)? I've tried defining bindings for __init and __call (the latter under a scope, to define it on the class, not its instances), but I didn't have success with either approach.

Was it helpful?

Solution

Constructors in Luabind must be actual C++ class constructors. So you'll just have to deal with the slight API weirdness.

If all you're interested in is the ability to use Foo as a constructor method, then you can do this. Register your C++ class Foo as FooLua to Lua. Then, register this someCreateMethod, not as a member of FooLua, but as just a Lua free function called Foo. Thus, as far as the user is concerned, Foo is a constructor for the Lua class Foo.

Now, this will inhibit your ability to give Foo other static properties, like members and so forth. But you could accomplish that by using some direct Lua API coding. You can create an empty table Foo and create a metatable for it that forwards __index and __newindex calls to FooLua. Similarly, you can override this metatable's __call to forward the construction to Foo.create.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top