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?
why didn't i see that! so simple...
RCIX
2009-08-16 03:30:07
wait, does that catch string keys and such?
RCIX
2009-08-16 03:30:38
yes, string keys are handled
Doug Currie
2009-08-16 03:35:42
This should work with some tweaking for handling subtables. Thanks!
RCIX
2009-08-16 06:17:57
+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
2009-08-16 06:26:35
Note that it is usually a bad idea to mess with standard Lua "namespaces" (like table.*). Better to make your own.
Alexander Gladysh
2009-08-16 07:37:15
"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
2009-08-17 18:08:15