Documentation for this module may be created at Module:DiceEval/doc
local p = {}
local function parseDice(s)
-- Accepts optional spaces and upper/lowercase 'd'
if type(s) ~= 'string' then
return nil, nil, "expected a string like '2d8'"
end
local n, m = s:match("^%s*(%d+)%s*[dD]%s*(%d+)%s*$")
if not n then
return nil, nil, "bad format (use NdM, e.g., '3d6')"
end
n, m = tonumber(n), tonumber(m)
if n <= 0 or m <= 0 then
return nil, nil, "n and m must be positive integers"
end
return n, m
end
local function compute(n, m)
return n * math.ceil((m + 1) / 2)
end
-- Public: {{#invoke:DiceMid|eval|2d8}}
function p.eval(frame)
local s = frame.args[1] or frame.args.s
if not s and frame.getParent then
local parent = frame:getParent()
if parent then s = parent.args[1] or parent.args.s end
end
local n, m, err = parseDice(s)
if not n then
return "Error: " .. err
end
return tostring(compute(n, m))
end
-- For other modules/tests: require('Module:DiceMid')._eval("3d6")
function p._eval(s)
local n, m, err = parseDice(s)
if not n then error(err) end
return compute(n, m)
end
return p