将C ++方法和变量并排绑定到表中

时间:2013-04-19 22:08:25

标签: c++ c lua

我一直在尝试创建一个“宿主”应用程序,它将C ++ API暴露给Lua代码,到目前为止已经相当成功,但在尝试用方法绑定“变量”时遇到了障碍。 / p>

我开发的用于将“类”绑定到lua的模式涉及每个类具有_new_gc函数,以及每个类的静态luaL_Reg RegData[]。然后我可以将所需的函数分配到RegData数组中,并调用辅助方法将它们绑定到lua。以下是一些说明我的方法的代码:

int Host::_new(lua_State * ls)
{
    Host ** udata = (Host **)lua_newuserdata(ls, sizeof(Host *);
    *udata = new Host();

    luaL_getmetatable(ls, "luaL_Host);
    lua_setmetatable(ls, -2);

    return 1;
}

int Host::_gc(lua_State * ls)
{
    Host * host = *(Host **)luaL_checkudata(ls, 1, "luaL_Host");
    delete host;
    return 0;
}

const luaL_Reg Host::RegistrationData[] =
{
    { "new"  , Host::_new },
    { "__gc" , Host::_gc  },
    { 0      , 0          }
};

其他地方:

void LuaState::registerObject(const char * name, const luaL_Reg data[])
{
    int len = strlen(name) + 6;
    char * luaLname = new char[len];
    snprintf(luaLname, len, "luaL_%s", name);

    // create the metatable with the proper functions
    luaL_newmetatable(_state, luaLname);
    luaL_setfuncs(_state, data, 0);

    // copy the metatable on the stack
    lua_pushvalue(_state, -1);
    // assign the index to the copy
    lua_setfield(_state, -1, "__index");

    // expose the table as the global "Host"
    lua_setglobal(_state, name);

    delete luaLname;
}

让我们说我希望我的Lua代码也能够查看键盘状态,并希望Lua代码访问它看起来像:

host = Host.new()
pressed = host.Keyboard.getKeyPressed(1)

将完全相同的模式复制到Keyboard类以设置键盘表变得很容易,但我似乎无法想出一个将Keyboard表添加到Host表的好方法。有没有一种简单的方法可以在不搞乱我的模式的情况下这样做?我应该使用更好的模式吗?

我已经找到了很多关于如何创建C-Lua API的各种不同方面的资源,但是在这样做时使用的模式/最佳实践并没有真正发现。另外,我知道有些图书馆,比如LuaBind,可以帮助解决这个问题,但我更喜欢自己做(至少是第一次)。

1 个答案:

答案 0 :(得分:0)

我决定采用更多的OO /继承方法解决这个问题,并计划看一下MOAI SDK如何实现他们的Lua API,这看起来很有希望。