将表从一个lua状态传递到另一个状态

时间:2014-07-19 15:01:03

标签: c++ lua lua-table

我有两个lua状态,比如L1和L2,我在L1中有一个复杂的表(包含其他表,或字符串和数字的表)。我想将此表传递给L2到C ++。除了在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表中的两个表时出错。如果我将对齐表更改为

Alignment = 
{
    Name = { x = -6, y = -10},
    Health = { x = -6, y = -7}
}

它可以工作,但当我删除x和y以将它们存储在索引1和2时,它会给出错误。任何人都可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您没有检测到所使用密钥的类型,并假设它是一个字符串。 lua_tostring将数字键转换为新表格中的字符串。

所以这个:

{"foo", "bar", "baz"}

成为这个:

{["1"]="foo", ["2"]="bar", ["3"]="baz"}

您还需要检查数字键(或其他键类型)。

此外,当将很多东西推到堆栈上时,请确保使用lua_checkstack function有足够的堆栈空间。默认情况下,Lua为您提供20,但如果您有更深的表,则可能会超出此限制并触发未定义的行为。

相关问题