Modul:Arguments: Perbedaan antara revisi

Konten dihapus Konten ditambahkan
Farras (bicara | kontrib)
nieuw
 
pesan galat tetap ditampilkan dalam bahasa Inggris, untuk mempermudah pemeliharaan
 
(6 revisi perantara oleh 3 pengguna tidak ditampilkan)
Baris 1:
-- This module provides easy processing of arguments passed to Scribunto from
--[[
-- #invoke. It is intended for use by other Lua modules, and should not be
-- called from #invoke directly.
 
local libraryUtil = require('libraryUtil')
This module provides a number of basic mathematical operations.
local checkType = libraryUtil.checkType
 
local arguments = {}
]]
 
-- Generate four different tidyVal functions, so that we don't have to check the
local yesno = require('Module:Yesno')
-- options every time we call it.
local getArgs = require('Module:Arguments').getArgs
 
local function tidyValDefault(key, val)
local p = {} -- Holds functions to be returned from #invoke, and functions to make available to other Lua modules.
if type(val) == 'string' then
local wrap = {} -- Holds wrapper functions that process arguments from #invoke. These act as intemediary between functions meant for #invoke and functions meant for Lua.
val = val:match('^%s*(.-)%s*$')
 
if val == '' then
--[[
return nil
Helper functions used to avoid redundant code.
else
]]
return val
 
local function err(msg)
-- Generates wikitext error messages.
return mw.ustring.format('<strong class="error">Formatting error: %s</strong>', msg)
end
 
local function unpackNumberArgs(args)
-- Returns an unpacked list of arguments specified with numerical keys.
local ret = {}
for k, v in pairs(args) do
if type(k) == 'number' then
table.insert(ret, v)
end
else
return val
end
return unpack(ret)
end
 
local function makeArgArraytidyValTrimOnly(...key, val)
if type(val) == 'string' then
-- Makes an array of arguments from a list of arguments that might include nils.
return val:match('^%s*(.-)%s*$')
local args = {...} -- Table of arguments. It might contain nils or non-number values, so we can't use ipairs.
else
local nums = {} -- Stores the numbers of valid numerical arguments.
return val
local ret = {}
for k, v in pairs(args) do
v = p._cleanNumber(v)
if v then
nums[#nums + 1] = k
args[k] = v
end
end
table.sort(nums)
for i, num in ipairs(nums) do
ret[#ret + 1] = args[num]
end
return ret
end
 
local function applyFuncToArgstidyValRemoveBlanksOnly(funckey, ...val)
if type(val) == 'string' then
-- Use a function on all supplied arguments, and return the result. The function must accept two numbers as parameters,
if val:find('%S') then
-- and must return a number as an output. This number is then supplied as input to the next function call.
return val
local vals = makeArgArray(...)
else
local count = #vals -- The number of valid arguments
return nil
if count == 0 then return
-- Exit if we have no valid args, otherwise removing the first arg would cause an error.
nil, 0
end
local ret = table.remove(vals, 1)
for _, val in ipairs(vals) do
ret = func(ret, val)
end
return ret, count
end
 
--[[
random
 
Generate a random number
 
Usage:
{{#invoke: Math | random }}
{{#invoke: Math | random | maximum value }}
{{#invoke: Math | random | minimum value | maximum value }}
]]
 
function wrap.random(args)
local first = p._cleanNumber(args[1])
local second = p._cleanNumber(args[2])
return p._random(first, second)
end
 
function p._random(first, second)
math.randomseed(mw.site.stats.edits + mw.site.stats.pages + os.time() + math.floor(os.clock() * 1000000000))
-- math.random will throw an error if given an explicit nil parameter, so we need to use if statements to check the params.
if first and second then
if first <= second then -- math.random doesn't allow the first number to be greater than the second.
return math.random(first, second)
end
elseif first then
return math.random(first)
else
return math.random()val
end
end
 
local function tidyValNoChange(key, val)
--[[
return val
order
 
Determine order of magnitude of a number
 
Usage:
{{#invoke: Math | order | value }}
]]
 
function wrap.order(args)
local input_string = (args[1] or args.x or '0');
local input_number = p._cleanNumber(input_string);
if input_number == nil then
return err('order of magnitude input appears non-numeric')
else
return p._order(input_number)
end
end
 
local function p._ordermatchesTitle(xgiven, title)
local tp = type( given )
if x == 0 then return 0 end
return (tp == 'string' or tp == 'number') and mw.title.new( given ).prefixedText == title
return math.floor(math.log10(math.abs(x)))
end
 
local translate_mt = { __index = function(t, k) return k end }
--[[
precision
 
function arguments.getArgs(frame, options)
Detemines the precision of a number using the string representation
checkType('getArgs', 1, frame, 'table', true)
checkType('getArgs', 2, options, 'table', true)
frame = frame or {}
options = options or {}
 
--[[
Usage:
-- Set up argument translation.
{{ #invoke: Math | precision | value }}
--]]
options.translate = options.translate or {}
if getmetatable(options.translate) == nil then
setmetatable(options.translate, translate_mt)
end
if options.backtranslate == nil then
options.backtranslate = {}
for k,v in pairs(options.translate) do
options.backtranslate[v] = k
end
end
if options.backtranslate and getmetatable(options.backtranslate) == nil then
setmetatable(options.backtranslate, {
__index = function(t, k)
if options.translate[k] ~= k then
return nil
else
return k
end
end
})
end
 
--[[
function wrap.precision(args)
-- Get the argument tables. If we were passed a valid frame object, get the
local input_string = (args[1] or args.x or '0');
-- frame arguments (fargs) and the parent frame arguments (pargs), depending
local trap_fraction = args.check_fraction;
-- on the options set and on the parent frame's availability. If we weren't
local input_number;
-- passed a valid frame object, we are being called from another Lua module
-- or from the debug console, so assume that we were passed a table of args
-- directly, and assign it to a new variable (luaArgs).
--]]
local fargs, pargs, luaArgs
if type(frame.args) == 'table' and type(frame.getParent) == 'function' then
if options.wrappers then
--[[
-- The wrappers option makes Module:Arguments look up arguments in
-- either the frame argument table or the parent argument table, but
-- not both. This means that users can use either the #invoke syntax
-- or a wrapper template without the loss of performance associated
-- with looking arguments up in both the frame and the parent frame.
-- Module:Arguments will look up arguments in the parent frame
-- if it finds the parent frame's title in options.wrapper;
-- otherwise it will look up arguments in the frame object passed
-- to getArgs.
--]]
local parent = frame:getParent()
if not parent then
fargs = frame.args
else
local title = parent:getTitle():gsub('/sandbox$', '')
local found = false
if matchesTitle(options.wrappers, title) then
found = true
elseif type(options.wrappers) == 'table' then
for _,v in pairs(options.wrappers) do
if matchesTitle(v, title) then
found = true
break
end
end
end
 
-- We test for false specifically here so that nil (the default) acts like true.
if yesno(trap_fraction, true) then -- Returns true for all input except nil, false, "no", "n", "0" and a few others. See [[Module:Yesno]].
if found or options.frameOnly == false then
local pos = string.find(input_string, '/', 1, true);
pargs = parent.args
if pos ~= nil then
if string.find(input_string, '/', pos + 1, true) == nil then
local denominator = string.sub(input_string, pos+1, -1);
local denom_value = tonumber(denominator);
if denom_value ~= nil then
return math.log10(denom_value);
end
if not found or options.parentOnly == false then
end
fargs = frame.args
end
end
else
-- options.wrapper isn't set, so check the other options.
if not options.parentOnly then
fargs = frame.args
end
if not options.frameOnly then
local parent = frame:getParent()
pargs = parent and parent.args or nil
end
end
if options.parentFirst then
fargs, pargs = pargs, fargs
end
end
 
input_number, input_string = p._cleanNumber(input_string);
if input_string == nil then
return err('precision input appears non-numeric')
else
luaArgs = frame
return p._precision(input_string)
end
end
 
function p._precision(x)
if type(x) == 'number' then
x = tostring(x)
end
x = string.upper(x)
 
-- Set the order of precedence of the argument tables. If the variables are
local decimal = x:find('%.')
-- nil, nothing will be added to the table, which is how we avoid clashes
local exponent_pos = x:find('E')
-- between the frame/parent args and the Lua args.
local result = 0;
local argTables = {fargs}
argTables[#argTables + 1] = pargs
argTables[#argTables + 1] = luaArgs
 
--[[
if exponent_pos ~= nil then
-- Generate the tidyVal function. If it has been specified by the user, we
local exponent = string.sub(x, exponent_pos + 1)
-- use that; if not, we choose one of four functions depending on the
x = string.sub(x, 1, exponent_pos - 1)
-- options chosen. This is so that we don't have to call the options table
result = result - tonumber(exponent)
-- every time the function is called.
end
--]]
 
local tidyVal = options.valueFunc
if decimal ~= nil then
if tidyVal then
result = result + string.len(x) - decimal
if type(tidyVal) ~= 'function' then
return result
error(
end
"bad value assigned to option 'valueFunc'"
 
.. '(function expected, got '
local pos = string.len(x);
.. type(tidyVal)
while x:byte(pos) == string.byte('0') do
.. ')',
pos = pos - 1
2
result = result - 1
)
if pos <= 0 then
return 0
end
elseif options.trim ~= false then
end
if options.removeBlanks ~= false then
 
tidyVal = tidyValDefault
return result
end
 
--[[
max
 
Finds the maximum argument
 
Usage:
{{#invoke:Math| max | value1 | value2 | ... }}
 
Note, any values that do not evaluate to numbers are ignored.
]]
 
function wrap.max(args)
return p._max(unpackNumberArgs(args))
end
 
function p._max(...)
local function maxOfTwo(a, b)
if a > b then
return a
else
tidyVal = tidyValTrimOnly
return b
end
else
end
if options.removeBlanks ~= false then
local max_value = applyFuncToArgs(maxOfTwo, ...)
tidyVal = tidyValRemoveBlanksOnly
if max_value then
return max_value
end
end
 
--[[
min
 
Finds the minimum argument
 
Usage:
{{#invoke:Math| min | value1 | value2 | ... }}
OR
{{#invoke:Math| min }}
 
When used with no arguments, it takes its input from the parent
frame. Note, any values that do not evaluate to numbers are ignored.
]]
 
function wrap.min(args)
return p._min(unpackNumberArgs(args))
end
 
function p._min(...)
local function minOfTwo(a, b)
if a < b then
return a
else
tidyVal = tidyValNoChange
return b
end
end
local min_value = applyFuncToArgs(minOfTwo, ...)
if min_value then
return min_value
end
end
 
--[[
-- Set up the args, metaArgs and nilArgs tables. args will be the one
average
-- accessed from functions, and metaArgs will hold the actual arguments. Nil
-- arguments are memoized in nilArgs, and the metatable connects all of them
-- together.
--]]
local args, metaArgs, nilArgs, metatable = {}, {}, {}, {}
setmetatable(args, metatable)
 
local function mergeArgs(tables)
Finds the average
--[[
 
-- Accepts multiple tables as input and merges their keys and values
Usage:
-- into one table. If a value is already present it is not overwritten;
{{#invoke:Math| average | value1 | value2 | ... }}
-- tables listed earlier have precedence. We are also memoizing nil
OR
-- values, which can be overwritten if they are 's' (soft).
{{#invoke:Math| average }}
--]]
 
for _, t in ipairs(tables) do
Note, any values that do not evaluate to numbers are ignored.
for key, val in pairs(t) do
]]
if metaArgs[key] == nil and nilArgs[key] ~= 'h' then
 
local tidiedVal = tidyVal(key, val)
function wrap.average(args)
if tidiedVal == nil then
return p._average(unpackNumberArgs(args))
nilArgs[key] = 's'
end
else
 
metaArgs[key] = tidiedVal
function p._average(...)
end
local function getSum(a, b)
end
return a + b
end
end
end
local sum, count = applyFuncToArgs(getSum, ...)
if not sum then
return 0
else
return sum / count
end
end
 
--[[
-- Define metatable behaviour. Arguments are memoized in the metaArgs table,
round
-- and are only fetched from the argument tables once. Fetching arguments
-- from the argument tables is the most resource-intensive step in this
-- module, so we try and avoid it where possible. For this reason, nil
-- arguments are also memoized, in the nilArgs table. Also, we keep a record
-- in the metatable of when pairs and ipairs have been called, so we do not
-- run pairs and ipairs on the argument tables more than once. We also do
-- not run ipairs on fargs and pargs if pairs has already been run, as all
-- the arguments will already have been copied over.
--]]
 
metatable.__index = function (t, key)
Rounds a number to specified precision
--[[
 
-- Fetches an argument when the args table is indexed. First we check
Usage:
-- to see if the value is memoized, and if not we try and fetch it from
{{#invoke:Math | round | value | precision }}
-- the argument tables. When we check memoization, we need to check
 
-- metaArgs before nilArgs, as both can be non-nil at the same time.
--]]
-- If the argument is not present in metaArgs, we also check whether
 
-- pairs has been run yet. If pairs has already been run, we return nil.
function wrap.round(args)
-- This is because all the arguments will have already been copied into
local value = p._cleanNumber(args[1] or args.value or 0)
-- metaArgs by the mergeArgs function, meaning that any other arguments
local precision = p._cleanNumber(args[2] or args.precision or 0)
-- must be nil.
if value == nil or precision == nil then
--]]
return err('round input appears non-numeric')
if type(key) == 'string' then
else
key = options.translate[key]
return p._round(value, precision)
end
local val = metaArgs[key]
end
if val ~= nil then
 
return val
function p._round(value, precision)
elseif metatable.donePairs or nilArgs[key] then
local rescale = math.pow(10, precision or 0);
return nil
return math.floor(value * rescale + 0.5) / rescale;
end
for _, argTable in ipairs(argTables) do
 
local argTableVal = tidyVal(key, argTable[key])
--[[
if argTableVal ~= nil then
mod
metaArgs[key] = argTableVal
 
return argTableVal
Implements the modulo operator
end
 
end
Usage:
nilArgs[key] = 'h'
{{#invoke:Math | mod | x | y }}
return nil
 
--]]
 
function wrap.mod(args)
local x = p._cleanNumber(args[1])
local y = p._cleanNumber(args[2])
if not x then
return err('first argument to mod appears non-numeric')
elseif not y then
return err('second argument to mod appears non-numeric')
else
return p._mod(x, y)
end
end
 
function p._mod(x, y)
local ret = x % y
if not (0 <= ret and ret < y) then
ret = 0
end
return ret
end
 
metatable.__newindex = function (t, key, val)
--[[
-- This function is called when a module tries to add a new value to the
gcd
-- args table, or tries to change an existing value.
 
if type(key) == 'string' then
Calculates the greatest common divisor of multiple numbers
key = options.translate[key]
 
Usage:
{{#invoke:Math | gcd | value 1 | value 2 | value 3 | ... }}
--]]
 
function wrap.gcd(args)
return p._gcd(unpackNumberArgs(args))
end
 
function p._gcd(...)
local function findGcd(a, b)
local r = b
local oldr = a
while r ~= 0 do
local quotient = math.floor(oldr / r)
oldr, r = r, oldr - quotient * r
end
if oldr < 0options.readOnly then
error(
oldr = oldr * -1
'could not write to argument table key "'
.. tostring(key)
.. '"; the table is read-only',
2
)
elseif options.noOverwrite and args[key] ~= nil then
error(
'could not write to argument table key "'
.. tostring(key)
.. '"; overwriting existing arguments is not permitted',
2
)
elseif val == nil then
--[[
-- If the argument is to be overwritten with nil, we need to erase
-- the value in metaArgs, so that __index, __pairs and __ipairs do
-- not use a previous existing value, if present; and we also need
-- to memoize the nil in nilArgs, so that the value isn't looked
-- up in the argument tables if it is accessed again.
--]]
metaArgs[key] = nil
nilArgs[key] = 'h'
else
metaArgs[key] = val
end
return oldr
end
local result, count = applyFuncToArgs(findGcd, ...)
return result
end
 
local function translatenext(invariant)
--[[
local k, v = next(invariant.t, invariant.k)
precision_format
invariant.k = k
 
if k == nil then
Rounds a number to the specified precision and formats according to rules
return nil
originally used for {{template:Rnd}}. Output is a string.
elseif type(k) ~= 'string' or not options.backtranslate then
 
return k, v
Usage:
else
{{#invoke: Math | precision_format | number | precision }}
local backtranslate = options.backtranslate[k]
]]
if backtranslate == nil then
 
-- Skip this one. This is a tail call, so this won't cause stack overflow
function wrap.precision_format(args)
return translatenext(invariant)
local value_string = args[1] or 0
else
local precision = args[2] or 0
return backtranslate, v
return p._precision_format(value_string, precision)
end
 
function p._precision_format(value_string, precision)
-- For access to Mediawiki built-in formatter.
local lang = mw.getContentLanguage();
 
local value
value, value_string = p._cleanNumber(value_string)
precision = p._cleanNumber(precision)
 
-- Check for non-numeric input
if value == nil or precision == nil then
return err('invalid input when rounding')
end
 
local current_precision = p._precision(value)
local order = p._order(value)
 
-- Due to round-off effects it is neccesary to limit the returned precision under
-- some circumstances because the terminal digits will be inaccurately reported.
if order + precision >= 14 then
orig_precision = p._precision(value_string)
if order + orig_precision >= 14 then
precision = 13 - order;
end
end
 
-- If rounding off, truncate extra digits
if precision < current_precision then
value = p._round(value, precision)
current_precision = p._precision(value)
end
 
local formatted_num = lang:formatNum(math.abs(value))
local sign
 
-- Use proper unary minus sign rather than ASCII default
if value < 0 then
sign = '−'
else
sign = ''
end
 
-- Handle cases requiring scientific notation
if string.find(formatted_num, 'E', 1, true) ~= nil or math.abs(order) >= 9 then
value = value * math.pow(10, -order)
current_precision = current_precision + order
precision = precision + order
formatted_num = lang:formatNum(math.abs(value))
else
order = 0;
end
formatted_num = sign .. formatted_num
 
-- Pad with zeros, if needed
if current_precision < precision then
local padding
if current_precision <= 0 then
if precision > 0 then
local zero_sep = lang:formatNum(1.1)
formatted_num = formatted_num .. zero_sep:sub(2,2)
 
padding = precision
if padding > 20 then
padding = 20
end
 
formatted_num = formatted_num .. string.rep('0', padding)
end
else
padding = precision - current_precision
if padding > 20 then
padding = 20
end
formatted_num = formatted_num .. string.rep('0', padding)
end
end
 
metatable.__pairs = function ()
-- Add exponential notation, if necessary.
-- Called when pairs is run on the args table.
if order ~= 0 then
if not metatable.donePairs then
-- Use proper unary minus sign rather than ASCII default
mergeArgs(argTables)
if order < 0 then
metatable.donePairs = true
order = '−' .. lang:formatNum(math.abs(order))
elseend
return translatenext, { t = metaArgs }
order = lang:formatNum(order)
end
 
formatted_num = formatted_num .. '<span style="margin:0 .15em 0 .25em">×</span>10<sup>' .. order .. '</sup>'
end
 
local function inext(t, i)
return formatted_num
-- This uses our __index metamethod
end
local v = t[i + 1]
 
if v ~= nil then
--[[
return i + 1, v
Helper function that interprets the input numerically. If the
input does not appear to be a number, attempts evaluating it as
a parser functions expression.
]]
 
function p._cleanNumber(number_string)
if type(number_string) == 'number' then
-- We were passed a number, so we don't need to do any processing.
return number_string, tostring(number_string)
elseif type(number_string) ~= 'string' or not number_string:find('%S') then
-- We were passed a non-string or a blank string, so exit.
return nil, nil;
end
 
-- Attempt basic conversion
local number = tonumber(number_string)
 
-- If failed, attempt to evaluate input as an expression
if number == nil then
local frame = mw.getCurrentFrame()
local attempt = frame:preprocess('{{#expr: ' .. number_string .. '}}')
attempt = tonumber(attempt)
if attempt ~= nil then
number = attempt
number_string = tostring(number)
else
number = nil
number_string = nil
end
else
number_string = number_string:match("^%s*(.-)%s*$") -- String is valid but may contain padding, clean it.
number_string = number_string:match("^%+(.*)$") or number_string -- Trim any leading + signs.
if number_string:find('^%-?0[xX]') then
-- Number is using 0xnnn notation to indicate base 16; use the number that Lua detected instead.
number_string = tostring(number)
end
end
 
metatable.__ipairs = function (t)
return number, number_string
-- Called when ipairs is run on the args table.
end
return inext, t, 0
 
--[[
Wrapper function that does basic argument processing. This ensures that all functions from #invoke can use either the current
frame or the parent frame, and it also trims whitespace for all arguments and removes blank arguments.
]]
 
local function makeWrapper(funcName)
return function (frame)
local args = getArgs(frame) -- Argument processing is left to Module:Arguments. Whitespace is trimmed and blank arguments are removed.
return wrap[funcName](args)
end
end
 
return args
for funcName in pairs(wrap) do
p[funcName] = makeWrapper(funcName)
end
 
return parguments