How to Merge Two Tables in Lua
Recently, I had the need to combine two tables in my Corona SDK app and unfortunately, there wasn’t a table function that already did this. If there is, please let me know in the comments! Anyways, here is a code snippet that you can use to combine two separate tables.
local colors = {}
colors[1] = "red"
colors[2] = "blue"
colors[3] = "green"
local otherColors = {}
otherColors[1] = "cyan"
otherColors[2] = "magenta"
otherColors[3] = "yellow"
otherColors[4] = "key"
function joinMyTables(t1, t2)
for k,v in ipairs(t2) do
table.insert(t1, v)
end
return t1
end
joinMyTables(colors, otherColors)
In the code above, I created two tables named colors and otherColors. Then I created a function called joinTables that will take the contents of the second table and put it at the end of the first table. I hope this little snippet of code can help you in your next Corona SDK app!
Update : Someone asked me how I used this function in my app. In my app, I had two text files that contained a list of first names and a list of last names. In the code, I was reading both files to a table and I needed a way to merge the contents of the tables to make a full name. And voila! That’s how I used joinMyTables() in a real world function using Corona SDK.
just what I needed.
You’re welcome!
Cool! But how can I merge three tables?
If you want to merge three tables using this code, you’ll have to merge two tables and then merge the last two tables. Let’s say you have tables A, B, and C. You’ll need to merge A with B, then merge the results with C.