Module:Utils: Difference between revisions

Fredg999 (talk | contribs)
Bug fixing
Fredg999 (talk | contribs)
Added input check, fixed how arguments work (I hope)
Line 1: Line 1:
local p = {}
local p = {}
-- evaluate input on error use default
local function eval_num_arg(input, def_value)
local result = input
if type(input) ~= 'number' then
result = def_value
if type(input) == 'string' then
input = input:match("^%s*(.-)%s*$")
if string.len(input) > 0 then
result = tonumber(input)
end
end
end
return result
end


-- return logarithm base b of x
-- return logarithm base b of x
function p.log(x, b)
function p.log(frame)
b = b or 2 -- defaults to base 2 (octave) if b is omitted
-- x defaults to 0 if omitted
local x = eval_num_arg(frame.args[1], 0)
-- b defaults to 2 ("octave") if omitted
local b = eval_num_arg(frame.args[2], 2)
return math.log(x)/math.log(b)
return math.log(x)/math.log(b)
end
end
Line 9: Line 27:
-- return x rounded to a precision of p decimal places
-- return x rounded to a precision of p decimal places
function p.round(x, prec)
function p.round(x, prec)
prec = prec or 3 -- default to 3 decimal places if prec is omitted
-- x defaults to 0 if omitted
local x = eval_num_arg(frame.args[1], 0)
-- prec defaults to 3 if omitted
local prec = eval_num_arg(frame.args[2], 3)
return math.floor(x*10^prec+0.5)/10^prec
return math.floor(x*10^prec+0.5)/10^prec
end
end


return p
return p