我有两个脚本,每个脚本都在不同的lua_State中。
我试图从一种状态中得到一个变量,并在另一种状态中使用它。
下面的代码适用于单变量和单向数组。我能得到一些指导,让它也工作在多维数组吗?
void getValues(lua_State* L1, lua_State* L2, int& returns)
{
if (lua_isuserdata(L1, -1))
{
LuaElement* e = Luna<LuaElement>::to_object(L1, -1);
if (e != NULL)
{
Luna<LuaElement>::push_object(L2, e);
}
}
else if (lua_isstring(L1, -1))
{
lua_pushstring(L2, lua_tostring(L1, -1));
}
else if (lua_isnumber(L1, -1))
lua_pushnumber(L2, lua_tonumber(L1, -1));
else if (lua_isboolean(L1, -1))
lua_pushboolean(L2, lua_toboolean(L1, -1));
else if (lua_istable(L1, -1))
{
lua_pushnil(L1);
lua_newtable(L2);
while (lua_next(L1, -2))
{
getValues(L1, L2, returns);
lua_rawseti(L2,-2,returns-1);
lua_pop(L1, 1);
}
// lua_rawseti(L2,-2,returns); // this needs work
}
returns++;
}不幸的是,我很难实现递归,才能使它在多维数组中工作。
发布于 2017-09-14 23:05:27
解决了。
对任何人来说,这可能是有用的:
void getValues(lua_State* L1, lua_State* L2, int ind)
{
if (lua_type(L1, -1) == LUA_TTABLE)
{
lua_newtable(L2);
lua_pushnil(L1);
ind = 0;
while (lua_next(L1, -2))
{
// push the key
if (lua_type(L1, -2) == LUA_TSTRING)
lua_pushstring(L2, lua_tostring(L1, -2));
else if (lua_type(L1, -2) == LUA_TNUMBER)
lua_pushnumber(L2, lua_tonumber(L1, -2));
else
lua_pushnumber(L2, ind);
getValues(L1, L2, ind++);
lua_pop(L1, 1);
lua_settable(L2, -3);
}
}
else if (lua_type(L1, -1) == LUA_TSTRING)
{
lua_pushstring(L2, lua_tostring(L1, -1));
}
else if (lua_type(L1, -1) == LUA_TNUMBER)
{
lua_pushnumber(L2, lua_tonumber(L1, -1));
}
else if (lua_type(L1, -1) == LUA_TBOOLEAN)
{
lua_pushboolean(L2, lua_toboolean(L1, -1));
}
else if (lua_type(L1, -1) == LUA_TUSERDATA)
{
// replace with your own user data. This is mine
LuaElement* e = Luna<LuaElement>::to_object(L1, -1);
if (e != NULL)
{
Luna<LuaElement>::push_object(L2, e);
}
}
}警告: L1和L2必须是不同的状态。
发布于 2017-09-14 06:36:41
你可以试试点缀::表:
https://stackoverflow.com/questions/46205435
复制相似问题