Corona SDK and other Game Development Tutorials

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)

   return t1
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.

1 Comment
  1. Great pice of code. I’m sure you helped a lot of people 🙂

Leave a Reply