0

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
hjpotter92
  • 78,589
  • 36
  • 144
  • 183

2 Answers2

1

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");
greatwolf
  • 20,287
  • 13
  • 71
  • 105
0

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.

W.B.
  • 5,445
  • 19
  • 29