C ++ Lua(对象表)

时间:2015-05-26 14:35:37

标签: c++ scripting lua

我想将对象矢量的矢量转换为Lua中的对象表格。

所以我在lua中有一个简单的脚本:

objects = getObjects()
explosion = objects[1][1]:getDestructible()
print (explosion)

这是我的.cpp文件

std::vector<std::vector<Area> > objects;
int x;
int y;

y = 0;
lua_newtable(L);
for (std::vector<std::vector<Area> >::iterator it = objects.begin(); it != objects.end(); ++it)
{
    lua_createtable(L, 2, 0);
    x = 0;
    for (std::vector<Area>::iterator it2 = it->begin(); it2 != it->end(); ++it2)
    {
        lua_newtable(L);
        luaL_getmetatable(L, "luaL_Object");
        lua_setmetatable(L, -2);
        lua_rawseti(L, -2, x + 1);
        x++;
    }
    lua_rawseti(L, -2, y);
    y++;
}

当我运行脚本时,我总是得到类似“尝试索引零索引”的内容。我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

感谢大家的帮助!我终于找到了问题的答案,就是这样:

int Lua::luaGetObjects(lua_State *L)
{
    int x;
    int y;

    y = 0;
    lua_newtable(L);
    for (std::vector<std::vector<Area> >::iterator it2 = objects.begin(); it2 != objects.end(); ++it2)
    {
        x = 0;
        lua_newtable(L);
        for (std::vector<Area>::iterator it = it2->begin(); it != it2->end(); it++, x++) 
        {

            lua_pushnumber(L, x);

            luaL_getmetatable(L, "luaL_Object");
            lua_setmetatable(L, -2);

            lua_rawseti(L, -2, x + 1);
            x++;
        }
        lua_rawseti(L, -2, y + 1);
        y++;
    }
    return 1;
}

我最后可以打电话给:

objects = getObjects()
explosion = objects[1][1]:getExplosion()
print(explosion)