简体   繁体   中英

Looping through tables in a table in Lua

I've hit a complete dead end with this. This is probably going to be something incredibly basic and it will most likely result in me smashing my head into a wall for having a major brain fart. My question is basically, how do you loop though tables in lua if the entries are tables themselves?

C++:

lua_newtable(luaState);
    for(auto rec : recpay) {
        lua_newtable(luaState);

        lua_pushnumber(luaState, rec.amount);
        lua_setfield(luaState, -2, "Amount");

        lua_pushnumber(luaState, rec.units);
        lua_setfield(luaState, -2, "Units");

        lua_setfield(luaState, -2, rec.type);
    }
lua_setglobal(luaState, "RecuringPayments");

Lua:

for _,RecWT in ipairs(RecuringPayments) do
    -- RecWT.Amount = nil?
end

In your C++ code it looks like you're setting the subtable by string as a key rather than by index. To traverse that entry you have to use pairs instead:

for recType, RecWT in pairs(RecuringPayments) do
  assert(RecWT.Amount ~= nil)
end

Note that ipairs only traverses the index part of the table, the associative part is ignored.

Alternatively, if you want to use index access then you have to set the key-value with lua_settable instead:

lua_newtable(luaState);
int i = 0;
for(auto rec : recpay)
{
    lua_newtable(luaState);

    lua_pushnumber(luaState, rec.amount);
    lua_setfield(luaState, -2, "Amount");

    lua_pushnumber(luaState, rec.units);
    lua_setfield(luaState, -2, "Units");

    lua_pushnumber(luaState, ++i);
    lua_insert(luaState, -2);
    lua_settable(luaState, -3);
}
lua_setglobal(luaState, "RecuringPayments");

You can use a recursive function that traverses tables:

function traversetable(tab, array)
    local iteratefunc = array and ipairs or pairs
    for k, v in iteratefunc(tab) do
        if type(v) == "table" then
            traversetable(v, array)    --Assumes that type is the same as the parent's table
        else
            --Do other stuff
        end
    end
end

This is just a basic example, but gives you a rough idea. array is a boolean value indicating, whether it's a one-based array or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM