table.update

Post Reply
Jor'Mox
Posts: 1146
Joined: Wed Apr 03, 2013 2:19 am

table.update

Post by Jor'Mox »

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:
Code: [show] | [select all] lua
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:
Code: [show] | [select all] lua
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:
Code: [show] | [select all] lua
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.

User avatar
Vadi
Posts: 5042
Joined: Sat Mar 14, 2009 3:13 pm

Re: table.update

Post by Vadi »

It looks like table.update(t1, t2) was being defined as table:update(t1, t2). Which is a bit quirky.

I'll replace it with your non-overwriting version as I don't think anyone was using this function before (due how it worked and it wasn't documented either).

Thank you!

Post Reply