3

Is there an easy way to concatenate two tables which are sequences? For example

a = {1, 2, 3}
b = {5, 6, 7}
c = cat(a,b)

where c would be the table {1,2,3,5,6,7}?

Wauzl
  • 941
  • 4
  • 20
  • 2
    Try having a look at [this](http://stackoverflow.com/questions/1283388/lua-merge-tables) and [this](http://stackoverflow.com/questions/1410862/concatenation-of-tables-in-lua) – Robin Gertenbach Jan 21 '16 at 10:33
  • 2
    Excellently and precisely worded question. Unfortunately, it is a duplicate of poorer quality questions. – Tom Blodget Jan 22 '16 at 00:05

1 Answers1

3
function cat(t, ...)  
    local new = {unpack(t)}  
    for i,v in ipairs({...}) do  
        for ii,vv in ipairs(v) do  
            new[#new+1] = vv  
        end  
    end  
    return new  
end

It uses iteration to add the elements of each array to a new one.

It's also worth noting that {unpack(t)} will only work if you have less than a specific number of elements, due to how tuples work in Lua. This varies across versions and depending on what you're doing, but if it's small you probably have nothing to worry about.

warspyking
  • 3,045
  • 4
  • 20
  • 37