Module:Util/tables/merge

From Zelda Wiki, the Zelda encyclopedia
Jump to navigation Jump to search

merge(tbl, ...)

Recursively merges tables.

Returns

  • tbl with merged values. Subsequent sources overwrite key assignments of previous sources.

Examples

#InputOutputResult
1
local tbl = {
  flib = "flob",
  foo = {
    bar = {"flib", "flob"},
    baz = {"quux", "quuz"},
  },
}
util.tables.merge(tbl, {
  foo = {
    bar = {"noot"},
    baz = "noot",
    wibble = "wobble",
  },
})
return tbl
{
  flib = "flob",
  foo = {
    wibble = "wobble",
    baz = "noot",
    bar = {"noot", "flob"},
  },
}
Common use: merging keys into new table.
2
merge({}, { flib = "flob" }, { wibble = "wobble" })
{
  flib = "flob",
  wibble = "wobble",
}

local function merge(tbl, ...)
	if tbl == nil then
		return nil
	end
	for i, source in ipairs({...}) do
		for k, v in pairs(source) do
			if type(v) == "table" and type(tbl[k]) == "table" then
				tbl[k] = merge({}, tbl[k], v)
			elseif type(v) == "table" then
				-- We make a clone of v rather than assign v directly in case source table is frame.args or mw.loadData which don't behave like normal tables
				-- It's simpler if this function can guarantee that the output table will be a normal table all the way down
				tbl[k] = merge({}, v)
			else
				tbl[k] = v
			end
		end
	end
	return tbl
end

return merge