【发布时间】:2014-07-21 08:42:05
【问题描述】:
我有两个 lua 状态,比如 L1 和 L2,我在 L1 中有一个复杂表(包含其他表或字符串和数字的表)。我想通过 C++ 将此表传递给 L2。除了在 C++ 中显式打开整个表然后将条目一一发送到 L2 之外,还有什么简单的方法可以做到这一点。
表格是这样的:
Property =
{
Name = "Ekans",
Stats =
{
HP = 300,
Attack = 50,
Defense = 30,
SpAttack = 20,
SpDefense = 30,
Speed = 60
},
Attributes =
{
LOS = 5;
Range = 1.5;
MoveDelay = 0;
},
Alignment =
{
Name = { -6, -10},
Health = { -6, -7}
}
}
我尝试使用此代码来执行此操作:
static void transferTable(lua_State *L1, lua_State *L2)
{
lua_pushnil(L1);
while (lua_next(L1, -2) != 0)
{
if (lua_isnumber(L1, -1))
{
cout << lua_tostring(L1, -2) << " : " << lua_tonumber(L1, -1) << endl;
lua_pushstring(L2, lua_tostring(L1, -2));
lua_pushnumber(L2, lua_tonumber(L1, -1));
lua_settable(L2, -3);
}
else if (lua_isstring(L1, -1))
{
cout << lua_tostring(L1, -2) << " : " << lua_tostring(L1, -1) << endl;
lua_pushstring(L2, lua_tostring(L1, -2));
lua_pushstring(L2, lua_tostring(L1, -1));
lua_settable(L2, -3);
}
else if (lua_istable(L1, -1))
{
cout << lua_tostring(L1, -2) << endl;
lua_pushstring(L2, lua_tostring(L1, -2));
lua_newtable(L2);
transferTable(L1, L2);
lua_settable(L2, -3);
}
lua_pop(L1, 1);
}
}
static int luaStats(lua_State* L)
{
//Exchanging tables from "entity->getLuaState()" to "L"
lua_getglobal(entity->getLuaState(), "Property");
lua_newtable(L);
transferTable(entity->getLuaState(), L);
lua_pop(entity->getLuaState(), 1);
return 1;
}
代码有效,但在尝试复制对齐表中的两个表时出错。如果我将对齐表更改为
Alignment =
{
Name = { x = -6, y = -10},
Health = { x = -6, y = -7}
}
它可以工作,但是当我删除 x 和 y 以将它们存储在索引 1 和 2 时,它会出错。有谁能解决这个问题吗?
【问题讨论】:
-
你确定这是你要使用的打印功能吗?你的 Lua 数字不是潜在的浮点数吗?
-
不,我基本上不打算打印。我的主要目标是发送完整的表格。当我在网上搜索时,我发现读取表中任何类型的值的通用函数都可以这样实现。但我不知道如何使用这些值并使用 C++ 创建它们的表,然后将其传递给另一个 LUA 状态。
-
您的问题是一般(反)序列化问题。我想你想要传输的唯一 Lua 数据是字符串、数字和表,它们只被引用一次。因此,序列化到本机缓冲区,反序列化随心所欲。 Google for
pickle获取 Lua 序列化方式。