Pergi ke kandungan

Modul:table/flatten

Daripada Wikikamus
local error = error
local insert = table.insert
local type = type

local function flatten(t, list, n, current)
	current[t] = true
	local i = 0
	while true do
		i = i + 1
		local v = t[i]
		if v == nil then
			current[t] = nil
			return n
		elseif type(v) ~= "table" then
			n = n + 1
			list[n] = v
		elseif current[v] then
			error("loop in input list")
		else
			n = flatten(v, list, n, current)
		end
	end
end

--[==[
Given a list, which may contain sublists, flatten it into a single list. For example, {flatten({ "a", { "b", "c" }, "d" })} ->
{ { "a", "b", "c", "d" }}]==]
return function(t)
	local list = {}
	flatten(t, list, 0, {})
	return list
end