Iterator Generator for Multiple Tables


  • This isn't cool, but I want to contribute so: The other day, when someone asked how you would loop more than one table in one for loop, I wrote an iterator generator function which allows you to use one for loop with multiple tables (a function > using this, I just wanted to see if I could).

    local function mpairs(...)
        local args, kvp = {...}, {};
        
        for _, v in next, args do
            if type(v) == 'table' then
                local t = {};
                local s;
                for k, v in next, v do
                    s = true;
                    t[#t+1] = {k, v};
                end;
                if s then
                    kvp[#kvp+1] = t;
                end;
            end;
        end;
        
        local i, m = 1, 1;
        return function()
            local pair = kvp[m][i];
            if pair then
                i = i + 1;
                return pair[1], pair[2];
            else
                m = m + 1;
                i = 1;
                if m > #kvp then
                    return;
                else
                    pair = kvp[m][i];
                    i = i + 1;
                    return pair[1], pair[2];
                end;
            end;
        end;
    end;
    

    This allows one to use a for loop like so,

    local t = {'Table 1 #1', '#2', '#3'};
    local t2 = {'Table 2 #1', '2: #2', '2: #3'};
    for i, v in mpairs(t, t2) do
        print(i, v);
    end;
    

    which would result in:

    1 'Table 1 #1'
    2 '#2'
    3 '#3'
    1 'Table 2 #1'
    2 '2: #2'
    3 '2: #3'


  • Oh, I see. Is there any reason why you would do this instead of using two generic for loops?

    And this is cool :P


  • @OldPalHappy Laziness?
    I would personally never use this; if I need to perform the same operations on a bunch of different tables I'd just create a function for it.

Log in to reply
 

Looks like your connection to Scripting Helpers was lost, please wait while we try to reconnect.