Reputation: 661
I have 2 scripts, each are in a different lua_State.
I am trying to be able to get a variable from one state and use it in the other.
My code below works for single variables and unidirectional arrays. Could I get some guidance on also making it work for multidimensional arrays?
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++;
}
Unfortunately I'm having a tough time getting the recursion right for this to work for multidimensional arrays.
Upvotes: 2
Views: 258
Reputation: 661
Solved.
For anyone this might be useful:
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);
}
}
}
Warning: L1 and L2 must be different states.
Upvotes: 2