Module:Util

来自滚动的天空Wiki
文档图示 模块文档[创建]

本模块还没有文档页面,你可以创建它。

您可以创建文档以让用户更好地理解本模块的用途。
编者可以在本模块的沙盒创建 | 镜像和测试样例创建页面进行实验。
请将模块自身所属的分类添加在文档中。本模块的子页面
local Util = {}

function Util.void() end

function Util.doNothing(...)
	return ...
end

function Util.forEach(t, f, ...)
	local m = getmetatable(t)
	if (type(m)=='table' and m.__foreach) then
		m.__foreach(t, f, ...)
	else
		for k,v in pairs(t) do
			f(k, v, ...)
		end
	end
end

function Util.forEachI(t, f, ...)
	local m = getmetatable(t)
	if (type(m)=='table' and m.__foreachi) then
		m.__foreachi(t, f, ...)
	else
		for k,v in ipairs(t) do
			f(k, v, ...)
		end
	end
end

function Util.multiIndex(t, ...)
	local result = t
	for i = 1, select('#',...) do
		local k = select(i, ...)
		if type(result)=='table' then
			result = result[k]
		else
			return nil
		end
	end
	return result
end

function Util.multiNewIndex(t, value, ...)
	local current = t
	for i = 1, select('#', ...) - 1 do
		local k = select(i, ...)
		if type(current[k])~='table' then
			current[k] = {}
		end
		current = current[k]
	end
	if type(current[k])~='table' then
		local k = select(-1, ...)
		current[k] = value
	end
	return type(value)=='table' and current[k] or t
end

function Util.addNewline(s)
	if s:match('^[*:;#]') or s:match('^{|') then
        return '\n' .. s ..'\n'
    else
        return s
	end
end

function Util.getNumberKeys(t)
	local nums = {}
	for k, v in pairs(t) do
		if type(k) == 'number' then
			nums[#nums + 1] = k
		end
	end
	table.sort(nums)
	return nums
end

function Util.sortedNumberIpairs(t)
	local nums = Util.getNumberKeys(t)
	local i = 0
	local lim = #nums
	return function ()
		i = i + 1
		if i <= lim then
			local key = nums[i]
			return key, t[key]
		else
			return nil, nil
		end
	end
end

return Util