Concatenation of tables in Lua programming


We can append two tables together in Lua with a trivial function, but it should be noted that no library function exists for the same.

There are different approaches to concatenating two tables in Lua. I’ve written two approaches that perform more or less the same when it comes to complexity.

The first approach looks something like this −

function TableConcat(t1,t2)
   for i=1,#t2 do
      t1[#t1+1] = t2[i]
   end
   return t1
end

Another approach of achieving the same is to make use of the ipairs() function.

Example

Consider the example shown below −

for _,v in ipairs(t2) do
   table.insert(t1, v)
end

We can use either of these approaches. Now let’s use the first one in a Lua example.

Example

Consider the example shown below −

 Live Demo

t1 = {1,2}
t2 = {3,4}
function TableConcat(t1,t2)
   for i=1,#t2 do
      t1[#t1+1] = t2[i]
   end
   return t1
end
t = TableConcat(t1,t2)
for _, v in pairs(t1) do print(v) end

Output

1
2
3
4

Updated on: 20-Jul-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements