Search code examples
lualua-table

How can I merge two tables like this? - Lua


I have these tables set like this

local tableone = {["Gold"] = 10, ["Gem"] = 5}
local tabletwo = {["Level"] = 1}

This is the code for merging

local test = {tableone, tabletwo}
print(test)

But if I try to merge the tables then the output is like this

[1] = {
   ["Gold"] = 10, 
   ["Gem"] = 5
},
[2] =  {
   ["Level"] = 1
}

And I would like to have the output like this

[1] = {
   ["Gold"] = 10, 
   ["Gem"] = 5,
   ["Level"] = 1
}

Is this possible? Sorry if I'm not that good at explaining.


Solution

  • You can do this with a simple nested loop.

    local function merge(...)
      local result <const> = {}
      -- For each source table
      for _, t in ipairs{...} do
        -- For each pair in t
        for k, v in pairs(t) do
          result[k] = v
        end
      end
      return result
    end
    
    local t <const> = {merge(tableone, tabletwo)}
    

    I put the result in a table constructor due to the [1] in the question.