Module:Util
Jump to navigation
Jump to search
Documentation for this module may be created at Module:Util/doc
--[[
A utility module that holds commonly used functions.
]]--
local p = {}
function p.spairs (dict, orderMethod)
-- collect the keys
local keys = {}
for k in pairs(dict) do keys[#keys+1] = k end
-- if orderMethod function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if orderMethod then
table.sort(keys, function(a,b) return orderMethod(dict, a, b) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], dict[keys[i]]
end
end
end
function p.searchForKeyOrValue (dict, param, value)
for k, v in pairs(dict) do
if v[param] == value or k == value then
return k
end
end
return nil
end
function p.getKeyFromPairs (dict, param, value)
return p.searchForKeyOrValue(dict, param, value)
end
function p.getValueFromPairs (dict, param, value)
return dict[p.searchForKeyOrValue(dict, param, value)]
end
function p.startsWith (str, start)
return string.sub(str,1,string.len(start))==start
end
function p.endsWith (str, ending)
return string.sub(str,#str-string.len(ending)+1,#str)==ending
end
function p.firstToUpper(str)
return (str:gsub("^%l", string.upper))
end
function p.arrayContains (arr, value)
for k, v in pairs(arr) do
if v == value then
return true
end
end
return false
end
function p.lengthOf (t)
local count = 0
for k,v in pairs(t) do count = count + 1 end
return count
end
return p