Module:Utils: Difference between revisions

ArrowHead294 (talk | contribs)
mNo edit summary
Fix for clamp. Improve documentation
 
(12 intermediate revisions by 2 users not shown)
Line 1: Line 1:
local p = {}
local get_args = require("Module:Arguments").getArgs
local get_args = require("Module:Arguments").getArgs
local p = {}
local yesno = require("Module:Yesno")
 
-- TODO??? Enforce rule for prefixing module-callable functions with an
-- underscore, regardless of whether a wrapper is needed or can be made????


-- Trim a string (remove leading and trailing, but not interior, whitespace)
-- Trim a string (remove leading and trailing, but not interior, whitespace)
Line 7: Line 12:
end
end


-- Check if a table contains x
-- Wrapper function for template access to [[Module:Yesno]]
function p.table_contains(tbl, x)
function p._yesno(frame)
for i = 1, #tbl do
return yesno(frame.args["input"], frame.args["default"])
if x == tbl[i] then
end
return true
 
-- Clamp function
-- Underscore-prefixed in case a wrapper for a template is ever needed
function p._clamp(value, min_value, max_value)
return math.min(math.max(value, min_value), max_value)
end
 
-- Check if a table contains the given value
-- Accepts an optional comparison function that accepts two tables, returning
-- true if value and tbl[i] have the same value.
function p.table_contains(tbl, value, compare_func)
if compare_func ~= nil then
-- Use compare function
for i = 1, #tbl do
if compare_func(value, tbl[i]) then
return true
end
end
else
-- No compare function
for i = 1, #tbl do
if value == tbl[i] then
return true
end
end
end
end
end
Line 18: Line 46:


-- Return the first index with the given value (or nil if not found)
-- Return the first index with the given value (or nil if not found)
function p.index_of(array, value)
-- Accepts an optional comparison function that accepts two tables, returning
for i, v in ipairs(array) do
-- true if value and v have the same value.
if v == value then
function p.index_of(array, value, compare_func)
return i
if compare_func ~= nil then
-- Use compare function
for i, v in ipairs(array) do
if compare_func(v, value) then
return i
end
end
else
-- No compare function
for i, v in ipairs(array) do
if v == value then
return i
end
end
end
end
end
Line 32: Line 72:
end
end


-- Return a link to Wikipedia in Wiki markup
-- Parse a ratio string like "3/2" into a number
function p.wlink(a, b)
-- Use default on error; cannot be used with {{#invoke:}}
return string.format("[[wikipedia:%s|%s]]", a, ((b == nil or p.trim(b) == "") and a or b)
)
end
 
-- Evaluate input on error use default; cannot be used with {{#invoke:}}
function p.eval_num_arg(input, def_value)
function p.eval_num_arg(input, def_value)
local result = input
local result = input