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.
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
Fooas a constructor method, then you can do this. Register your C++ classFooasFooLuato Lua. Then, register thissomeCreateMethod, not as a member ofFooLua, but as just a Lua free function calledFoo. Thus, as far as the user is concerned,Foois a constructor for the Lua classFoo.Now, this will inhibit your ability to give
Fooother static properties, like members and so forth. But you could accomplish that by using some direct Lua API coding. You can create an empty tableFooand create a metatable for it that forwards__indexand__newindexcalls toFooLua. Similarly, you can override this metatable’s__callto forward the construction toFoo.create.