Lua - Merging Arrays
We can append two arrays or 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. We've two approaches that can 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 - Merging Arrays
Consider the example shown below −
main.lua
-- initialize two arrays
t1 = {1,2}
t2 = {3,4}
-- concatenate the tables
function tableConcat(t1,t2)
-- loop over t2 items
for i=1,#t2 do
-- append entries to t1
t1[#t1+1] = t2[i]
end
-- return merged table
return t1
end
-- call the function to concatenate arrays
t = tableConcat(t1,t2)
-- print the merged values
for _, v in pairs(t1) do
print(v)
end
Output
When we run the above program, we will get the following output −
1 2 3 4
Example - Merging Arrays using ipairs()
Consider the example shown below −
main.lua
-- initialize two arrays
t1 = {1,2}
t2 = {3,4}
-- concatenate the tables
function tableConcat(t1,t2)
-- loop over t2 items
for _,v in ipairs(t2) do
-- append entries to t1
table.insert(t1, v)
end
-- return merged table
return t1
end
-- call the function to concatenate arrays
t = tableConcat(t1,t2)
-- print the merged values
for _, v in pairs(t1) do
print(v)
end
Output
When we run the above program, we will get the following output −
1 2 3 4
Advertisements