Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate table sequences in lua [duplicate]

Tags:

lua

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}?

like image 990
Wauzl Avatar asked Aug 29 '26 03:08

Wauzl


1 Answers

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.

like image 125
warspyking Avatar answered Sep 04 '26 19:09

warspyking



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!