-- Combine values from ... into one
function table.combine(t, ...)
	for _, to in ipairs{...} do
		for i=1, #to do
			t[#t+1] = to[i]
		end
	end
	return t
end

-- Update all keys in t with values from ...
function table.update(t, ...)
	for _, to in ipairs{...} do
		for k,v in pairs(to) do
			t[k] = v
		end
	end
	return t
end

-- Update all nil keys in t with values from ...
function table.update_nil(t, ...)
	for _, to in ipairs{...} do
		for k,v in pairs(to) do
			if t[k] == nil then
				t[k] = v
			end
		end
	end
	return t
end

-- Recursively meld table with ...
function table.meld(t, ...)
	for _, to in ipairs{...} do
		for k,v in pairs(to) do
			if type(t[k]) == "table" and type(v) == "table" then
				t[k] = table.meld(t[k], v)
			else
				t[k] = v
			end
		end
	end
	return t
end

-- A pairs() implementation that returns keys sorted
-- f is an alternative order function (optional)
-- <https://www.lua.org/pil/19.3.html>
function table.pairs_by_keys(t, f)
	local a = {}
	for n in pairs(t) do
		a[#a+1] = n
	end

	table.sort(a, f)

	local i = 0
	local function iter()
		i = i + 1
		if a[i] == nil then
			return
		else
			return a[i], t[a[i]]
		end
	end
	return iter
end
pairs_by_keys = table.pairs_by_keys
