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