1

I am trying to copy the contents of the source table to the dest table, overwriting keys that are the same and leaving different keys intact. I've messed about with a few things but can't figure it out. Can somebody help me?

local source = {
  version = 1,
  nest = {
    a = 5,
    b = 1,
    c = 0
    },
}

local dest = {
  version = 0,
  doesNotChange = 9,
  nest = {
    a = 0,
    b = 0,
    c = 0,
    d = "does not change"
  },
}
  • Take a look at James's answer here https://stackoverflow.com/questions/1283388/lua-merge-tables – xpqz Jul 04 '17 at 06:34
  • Awesome, thanks. I can't believe I didn't find that myself. –  Jul 04 '17 at 07:20

1 Answers1

2

You can use a generic for statement to achieve what you want.

The loop will iterate over all keys in sourceTable and asign the respective value to destinationTable. As you only index keys of sourceTable you cannot overwrite fields of destinationTable that have unique keys but you overwrite fields that exist in both tables and add new fields that only exist in sourceTable.

for k,v in pairs(sourceTable) do

  destinationTable[k] = v

end
Piglet
  • 27,501
  • 3
  • 20
  • 43