I noticed there was a table.update() function, but that it didn't seem to work. So, I cloned it and then tweaked it until it worked in a way that seemed to be reasonable. I made two versions, one overwrites the table to be updated, the other returns a new table that would result from updating the first table with data from the second table.
The non-overwriting version:
function table.update(t1, t2)
local tbl = {}
for k,v in pairs(t1) do
tbl[k] = v
end
for k,v in pairs(t2) do
if type(v) == "table" then
tbl[k] = table.update(tbl[k] or {}, v)
else
tbl[k] = v
end
end
return tbl
end
The overwriting version:
function table.update(tbl, t2)
for k,v in pairs(t2) do
if type(v) == "table" then
tbl[k] = table.update(tbl[k] or {}, v)
else
tbl[k] = v
end
end
end
An example script using the non-overwriting version of this function, to demonstrate results:
local tbl1 = {name = "name", age = 1, gender = "gender", shoe_size = 1, days = {1,3,5}}
local tbl2 = {name = "bob", gender = "male", age = 8, grade = 2, days = {1,4,6,7}, hair_color = "red"}
local tbl3 = table.update(tbl1,tbl2)
display(tbl1)
display(tbl3)
As can be seen by looking at the results, tbl1 remains unchanged, and tbl3 has the fields in tbl1 that are in tbl2 replaced with the new values, the other fields in tbl1 unchanged, and the new field from tbl2. I.E. this is a proper "update" in that new fields are added as necessary, old values are updated with new values, and any values not included in the update are left untouched.
Given that this function cannot be used as a method (I cannot call tbl1:update(tbl2) for instance), I personally think that the non-overwriting version is more appropriate. Either way, feel free to include this in future versions if desired, or use personally until such a time as the regular table.update() function is made operational.