Merging dictionaries

Arrays and collections / Dictionaries

local d1 = {first = "one"}
local d2 = {second = "two"}
local d3 = {third = "three"}

-- A new table gets the pairs of a, then of b
local function merge(a, b)
  local result = {}
  for key, value in pairs(a) do
    result[key] = value
  end
  for key, value in pairs(b) do
    result[key] = value
  end
  return result
end

local d_all = merge(d1, d2)
-- d_all.first = one
-- d_all.second = two

-- In place: copy into the existing table
for key, value in pairs(d3) do
  d_all[key] = value
end
-- d_all.third = three

-- d1 is untouched
-- d1.second = nil

-- The same key: the second table wins
local clash = merge(d1, {first = "ONE"})
-- clash.first = ONE

print("d_all.first = " .. d_all.first)
print("d_all.second = " .. d_all.second)
print("d_all.third = " .. d_all.third)
print("d1.second = " .. tostring(d1.second))
print("clash.first = " .. clash.first)