Lua - Merge Tables
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.
First Approach - Using for loop
The first approach looks something like this −
-- create a function to concatenate tables
function TableConcat(t1,t2)
for i=1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
Second Approach - Using ipairs()
Another approach of achieving the same is to make use of the ipairs() function.
-- use ipairs 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 - Using pairs iterator
Consider the example shown below −
main.lua
-- initialize first array
t1 = {1,2}
-- initialize second array
t2 = {3,4}
-- define a function to concatenate tables
function TableConcat(t1,t2)
for i=1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
-- concatenate tables
t = TableConcat(t1,t2)
-- iterate through table
for _, v in pairs(t1)
do
print(v)
end
Output
When we run the above code, we will get the following output−
1 2 3 4
Now let's use the second one in a Lua example.
Example - Using ipairs iterator
Consider the example shown below −
main.lua
-- initialize first array
t1 = {1,2}
-- initialize second array
t2 = {3,4}
-- iterate t2
for _,v in ipairs(t2)
do
table.insert(t1, v)
end
-- iterate t1 and print merged table
for _, v in pairs(t1)
do
print(v)
end
Output
When we run the above code, we will get the following output−
1 2 3 4
Advertisements