开发者

Register non-static C++ methods in Lua

I'm trying to make a small C++/Lua system where I would create my objects and attach behaviors to them in Lua. Right now I'm using LuaWrapper (a small header with basic C++ to Lua stuff), my problem is that as far as I can see Lua only let me register static class methods (or non-static functions), a little research and I figured its because the Lua typedef expects a method with only one parameter lua_State* L and non-static methods have the implicit this.

I was hoping for a way to solve this without dependency on other libraries, all I need is non-static classes/propertie开发者_如何学编程s in Lua, so I see no reason to use LuaBind+Boost or other heavy-dependant wrappers.


LuaWrapper isn't meant to hook up directly to non-static functions in a class. I suppose it could be with some special trickery, but this is how I designed it to be used:

static int Widget_AddChild(lua_State* L)
{
    Widget* parent = luaW_check<Widget>(L, 1);
    Widget* child = luaW_check<Widget>(L, 2);
    if (parent && child)
    {
        lua_pushboolean(L, parent->AddChild(child));
        return 1;
    }
    return 0;
}

// ...

static luaL_reg Widget_metatable[] =
{
    { "AddChild", Widget_Addchild },
    // ...
    { NULL, NULL }
};

I usually keep the non-lua stuff in a separate file. In this case Widget.cpp/hpp. Then I have a LuaWidget file which just contains bindings like these which I write as needed. (I also have a number of snipmate snippets to make writing these functions quick and painless. If you're using vim I'd be happy to share them)


You can make a static function that will accept an instance of the class and an argument and call that function on the instance:

void func_static(MyClass* inst, T arg) {
    inst->func(arg);
}

Then register a function to call that function as a metafunction so you can do in lua

blah:x(y)

which will call the function that will receive the userdata that blah contains, as well as the argument y, and call func_static with blah and y.


You may want to look into using toLua++ (http://www.codenix.com/~tolua/).

It can parse class definitions and output a c++ code file to make the non-static class members available in Lua.


You could also take a look at LuaCppWrapper. It's intended for simple bindings only. If you want a full fledged solution, maybe OOLua or Simple Lua Binder are what you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜