【问题标题】:How to return a table of tables to Lua from C/C++ function, through a for loop如何通过 for 循环从 C/C++ 函数将表返回到 Lua
【发布时间】:2012-10-30 20:17:48
【问题描述】:

我有一个 std::list 对象,我想给 Lua 一个返回其 2D 位置的函数。 所以我需要创建一个表

{ {x,y}, {x,y}, {x,y}...}

而且由于它都在一个列表中,我需要在迭代列表时创建它..

    lua_newtable(L_p);  // table at 0
    int tableIndex = 1; // first entry at 1

    for(    std::list<AmmoDropped*>::iterator it = m_inputAmmosDropped.begin();
            it != m_inputAmmosDropped.end();
            ++it ){

        // what do I do here

        ++tableIndex;
    }

    // returns the table
    return 1;

由整数键和'x'和'y'索引:

 positions[0].x
 positions[0].y

我通过反复试验尝试,但由于我现在不知道/不知道如何调试它,我真的迷路了。

【问题讨论】:

标签: c++ lua


【解决方案1】:

它会是这样的:

lua_newtable(L);    // table at 0
int tableIndex = 1; // first entry at 1

for(std::list<AmmoDropped*>::iterator it = m_inputAmmosDropped.begin();
      it != m_inputAmmosDropped.end();
      ++it ){
    lua_createtable(L, 2, 0);  // a 2 elements subtable
    lua_pushnumber(L, it->x);
    lua_rawseti(L, -2, 1);     // x is element 1 of subtable
    lua_pushnumber(L, it->y);
    lua_rawseti(L, -2, 2);     // y is element 2 of subtable
    lua_rawseti(L, -3, tableIndex++)    // table {x,y} is element tableIndex
}
return 1;

警告:这是我头脑中未经测试的代码...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-09
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-28
    • 2018-12-06
    • 2017-05-09
    相关资源
    最近更新 更多