Module:Util/tables/concat

From Zelda Wiki, the Zelda encyclopedia
Revision as of 17:06, 12 May 2024 by PhantomCaleb (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

concat(array, ...)

Returns

  • Creates a new array concatenating array with any additional arrays and/or values.

Examples

#InputOutputResult
1
return util.tables.concat({1}, 2, {3, 4}, {{5}}, {6})
{
  1,
  2,
  3,
  4,
  {5},
  6,
}
Tables with only string keys are treated as single values.
2
concat({}, {1, 2}, {3, 4, foo = "bar"}, { foo = "quux" })
{
  1,
  2,
  3,
  4,
  { foo = "quux" },
}

-- Returns true iff tbl is iterable as an array
local function isArray(tbl)
	if type(tbl) ~= "table" then
		return false
	end
	for i in ipairs(tbl) do
		return true
	end
	for k in pairs(tbl) do
		return false 
	end
	return true -- empty tbl ({}) should be considered an array for the purposes of concat
end

local function concat(...)
	local newtbl = {}
	for i, tbl in ipairs({...}) do
		if isArray(tbl) then
			for i, v in ipairs(tbl) do
				table.insert(newtbl, v)
			end
		else 
			table.insert(newtbl, tbl)
		end
	end
	return newtbl
end

return concat