tags:

views:

1168

answers:

2

I need to merge two tables, with the contents of the second overwriting contents in the first if a given item is in both. I looked but the standard libraries don't seem to offer this. Where can i get such a function?

+6  A: 
for k,v in pairs(second_table) do first_table[k] = v end
Doug Currie
why didn't i see that! so simple...
RCIX
wait, does that catch string keys and such?
RCIX
yes, string keys are handled
Doug Currie
This should work with some tweaking for handling subtables. Thanks!
RCIX
+1  A: 

Here's what i came up with based on Doug Currie's answer:

function tableMerge(t1, t2)
    for k,v in pairs(t2) do
     if type(v) == "table" then
      if type(t1[k] or false) == "table" then
       tableMerge(t1[k] or {}, t2[k] or {})
      else
       t1[k] = v
      end
     else
      t1[k] = v
     end
    end
    return t1
end
RCIX
Note that it is usually a bad idea to mess with standard Lua "namespaces" (like table.*). Better to make your own.
Alexander Gladysh
"if not t1[k] then t1[k] = {} end" contains a subtle bug (find it!)Better write it as "t1[k] = t1[k] or {}".Also, what happens if t2[k] is a table but t1[k] exists but is not a table?Finally, "table1[k] = v" should be "t1[k] = v".
lhf
All good points, i'll fix them immediately.
RCIX