C ++ Lua (object table table)
I want to convert a vector of a vector of objects to a table of objects table in Lua.
So, I have a simple script in lua:
objects = getObjects()
explosion = objects[1][1]:getDestructible()
print (explosion)
And this is my .cpp file
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++;
}
When I run the script, I always get something like "Attempting to index nil index". Did I miss something?
+3
source to share
1 answer
Thanks everyone for your help! I finally found the answer to my question, here it is:
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;
}
With which I can finally call the call:
objects = getObjects()
explosion = objects[1][1]:getExplosion()
print(explosion)
+2
source to share