Module:Utils: Difference between revisions
ArrowHead294 (talk | contribs) mNo edit summary |
Fix for clamp. Improve documentation |
||
| (4 intermediate revisions by one other user not shown) | |||
| Line 3: | Line 3: | ||
local get_args = require("Module:Arguments").getArgs | local get_args = require("Module:Arguments").getArgs | ||
local yesno = require("Module:Yesno") | 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 14: | Line 17: | ||
end | end | ||
-- Check if a table contains | -- Clamp function | ||
function p.table_contains(tbl, | -- Underscore-prefixed in case a wrapper for a template is ever needed | ||
for i = 1, #tbl do | function p._clamp(value, min_value, max_value) | ||
if | 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 25: | 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) | ||
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 39: | Line 72: | ||
end | end | ||
-- | -- Parse a ratio string like "3/2" into a number | ||
-- Use default on error; 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 | ||