How to create nested Lua tables using the C API

前端 未结 3 1626
北海茫月
北海茫月 2020-12-13 11:20

I want to create a table like

myTable = {
    [0] = { [\"a\"] = 4, [\"b\"] = 2 },
    [1] = { [\"a\"] = 13, [\"b\"] = 37 }
}

using the C AP

3条回答
  •  伪装坚强ぢ
    2020-12-13 12:05

    Here is something generic I came up to solve a similar problem, based on lhf's answer. This will create a Lua table for the form

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

    With arbitrary table/sub table length.

    int list_of_lists_to_lua(lua_State* L, const std::vector>& convertme) {
        lua_newtable(L);
        int counter = 0;
        for (const std::vector& list : convertme) {
            lua_pushnumber(L, ++counter);
            lua_newtable(L);
            int counter2 = 0;
            for (const std::string& item : list) {
                lua_pushnumber(L, ++counter2);
                lua_pushstring(L, item);
                lua_settable(L,-3);
            }
            lua_settable(L,-3);
        }
        return 1;
    }
    

提交回复
热议问题