【发布时间】:2015-08-08 07:23:34
【问题描述】:
我想将对象向量的向量转换为 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++;
}
当我运行脚本时,我总是会得到类似“尝试索引零索引”的信息。我错过了什么吗?
【问题讨论】:
-
你在哪里将实际对象推入堆栈,然后将其放入内表?您创建外部表,然后创建内部表并为它们提供元表,但您永远不会用任何内容填充它们(或者元表是否应该处理该访问?)。如果是这种情况,您确定元表正在工作吗?如果将索引拆分为多个步骤,哪个步骤会失败?
-
是的,元表包含所有我想使用的方法我很确定它可以工作,因为它可以用于简单的向量列表。我不确定如何测试哪个步骤失败?我的意思是这不只是索引的问题吗?
-
@Alex:你的 Lua 堆栈在内部循环中仍然不平衡:你压入一个值(
luaL_getmetatable),然后弹出一个值(lua_setmetatable),然后弹出另一个值(lua_rawseti)。您可能在luaL_getmetatable之前缺少lua_newtable或lua_newuserdata。最后一个lua_rawseti中的堆栈索引也应该是-2。 -
@siffiejoe:我已经调整了我上面的代码,考虑到你在说什么,但我有点迷茫,我也尝试了 print(type(objects[1])) 这给了我 nil ,所以第一个索引不起作用......有什么想法吗?!
-
与您的内部
lua_rawseti(L, -2, x + 1); x++;相比,外部lua_rawseti(L, -2, y); y++;可能存在一个错误