본문으로 이동

모듈:table/maxIndex

위키낱말사전, 말과 글의 누리

이 모듈에 대한 설명문서는 모듈:table/maxIndex/설명문서에서 만들 수 있습니다

local math_module = "Module:math"

local maxn = table.maxn
local pairs = pairs

local function is_positive_integer(...)
	is_positive_integer = require(math_module).is_positive_integer
	return is_positive_integer(...)
end

--[==[
Returns the highest positive integer index of a table or array that possibly has holes in it, or otherwise 0 if no positive integer keys are found. Note that this differs from `table.maxn`, which returns the highest positive numerical index, even if it is not an integer.]==]
if maxn == nil then
	return function(t)
		local max_key = 0
		for k in pairs(t) do
			if is_positive_integer(k) and k > max_key then
				max_key = k
			end
		end
		return max_key
	end
else -- table.maxn() is deprecated, but use it if it's available
	return function(t)
		-- Quick check: if maxn() returns an integer >= 0, return it.
		local max_key = maxn(t)
		if is_positive_integer(max_key, "include_0") then
			return max_key
		end
		-- Slow check.
		max_key = 0
		for k in pairs(t) do
			if is_positive_integer(k) and k > max_key then
				max_key = k
			end
		end
		return max_key
	end
end