How to extend tables?

How do I extend tables or combine tables?

Example:

local TableA = {1,2,3}
local TableB = {4,5,6}
Combine(TableA, TableB)
--> {1, 2, 3, 4, 5, 6}

You have to make your own function for that. I’d recommend a variadic function just in case if you have more than just two tables to combine.

local function combine(...)

    local args = {...}
    local combined = args[1] --the first table

    for i = 2, #args do --start at two because we already set combined as the first

        for i, v in pairs(args[i]) do --go through that table

            table.insert(combined, v) --add each index to combined 

        end

    end

    return combined

end

Combine({1, 2, 3}, {4, 5, 6}, {7, 8, 9}) --as many tables as you would like!

--note: it will be in the order you give the arguments to the function
2 Likes