Lua中的就地初始化表顺序

我想要做到以下:

MyObject:SetSize( { 10.0, 20.0 } )

但当我在 C 端遍历时 (SetSize 是一个 C 函数),参数的顺序是随机的。

这里是 C++ 处理表格的代码:

glm::vec2 State::PopVec2()
{
    glm::vec2 v();

    lua_pushnil( ls ); // first key

    int i = 0;
    while( lua_next( ls, -2 ) ) // pops key and pushes next key and value
    {
        // v[0] is x coordinate. v[1] is y coordinate.
        v[i] = (float)lua_tonumber( ls, -1 ); // get number

        lua_pop( ls, 1 );// pop value but leave next key.

        ++i;
    }

    lua_pop( ls, 1 ); // pop table

    return v;
}

如何确保一致的顺序,而不必在 Lua 端弄乱代码? (所以基本上在 C++ 端解决这个问题)

或者,我应该在 Lua 端使用什么作为“Vec2”等价物?

点赞
用户298661
用户298661

你应该将 1 和 2 推入栈中(或者如果表是从 0 开始的,则推入 0,1),并且使用 lua_geti 而不是使用 lua_next 迭代表。另一个你当前代码不正确的例子是如果 Lua 用户传递 {1, 2, 3}?这时你会访问 2 元素向量的第三个元素。

2015-06-07 20:48:05