Anonymous user
Module:Convert: Difference between revisions
massive refactor; as much as possible, handle input and output unit in the same way; handle combinations (todo: ftin)
(fix default expressions so they do not use loadstring (not available in Scribunto)) |
(massive refactor; as much as possible, handle input and output unit in the same way; handle combinations (todo: ftin)) |
||
Line 1:
-- Convert a value from one unit of measurement to another.
-- Example: {{convert|123|lb|kg}} --> 123 pounds (56 kg)
-- Conversion data is defined in another module because it is too large
Line 12 ⟶ 7:
local convertdata = require(is_test_run and "convertdata" or "Module:Convertdata")
local units = convertdata.units
local
local link_exceptions = convertdata.link_exceptions
local MINUS = '−' -- Unicode U+2212 MINUS SIGN (UTF-8: e2 88 92)
local function strip(text)
Line 128 ⟶ 126:
-- Return text with Unicode minus instead of '-', if present.
if text:sub(1, 1) == '-' then
return
end
return text
Line 218 ⟶ 216:
local function format_number(show, exponent, isnegative)
-- Return
-- s = wikitext formatted to display the value implied by the arguments:
-- exponent is nil; and
-- show is a string of digits (no sign), with an optional dot;
-- or:
--
-- show is a
-- implied dot before show; show does not start with '0').
-- f = true if s uses scientific notation
-- The formatted result:
-- * Includes a Unicode minus if isnegative.
-- * Has numsep inserted where necessary.
Line 233:
local sign
if isnegative then
sign =
else
sign = ''
Line 269:
if exponent > 10 or exponent <= -4 or (exponent == 10 and show ~= '1000000000') then
-- Rounded value satisfies: value >= 1e9 or value < 1e-4 (1e9 = 0.1e10).
return sign .. with_exponent(show, exponent-1), true
end
if exponent >= #show then
Line 339:
local wikitext
if wholestr then
local sign = negative and
if negative then
wholestr = change_sign(wholestr)
Line 345:
wikitext = frac2:format(use_minus(wholestr), sign, numstr, denstr)
else
local sign = negative and
wikitext = frac1:format(sign, numstr, denstr)
end
Line 355:
local function extract_number(args, index, which)
-- Return true, info if
-- where info is a table with the result.
-- Otherwise, return false, message.
-- Parameter 'which' (1 or 2) selects which input value is being
-- processed (to select the appropriate error message, if needed).
-- Before processing, the input text is cleaned:
-- * Any thousand separators (valid or not) are removed.
Line 363 ⟶ 365:
-- '-' (if negative) or '' (otherwise).
-- That replaces Unicode minus with '-'.
-- If successful,
--
-- singular = true if value is 1 (to use singular form of units)
-- = false if value is -1 (like old template)
-- clean = cleaned text with any separators and sign removed
--
-- For show:
-- * Thousand separators are inserted.
-- * If negative, a Unicode minus is used; otherwise the sign
Line 392:
end
local propersign, negative
if sign ==
propersign =
negative = true
elseif sign == '+' then
Line 414:
end
if show == nil then
singular = (value == 1 and not negative)
show = propersign .. with_separator(clean)
end
Line 420:
value = -value
end
end
Line 446 ⟶ 440:
local function get_parms(pframe)
-- If successful, return true, args, unit where
--
--
--
-- otherwise, return false, message.
-- Some of the named args that are added here could be provided by the
-- user of the template.
-- MediaWiki removes leading and trailing whitespace from the values of
-- named arguments. However, the values of numbered arguments include any
Line 463 ⟶ 460:
['+/-'] = {' ± ', ' ± '},
}
local success,
local args = {} -- arguments passed to template
for k, v in pframe:argumentPairs() do
args[k] = v
end
success,
if not success then return
local in_unit, precision
local next = strip(args[2])
Line 478 ⟶ 475:
else
args.range = range
success,
if not success then return
in_unit = strip(args[4])
i = 5
end
local success, in_unit_table = units:lookup(in_unit, args.sp)
if not success then return false, in_unit_table end
in_unit_table.valinfo = { info1, info2 } -- info2 is nil if no range
in_unit_table.inout = 'in' -- this is an input unit
next = strip(args[i])
i = i + 1
Line 496 ⟶ 495:
else
precision = next
end
if args.adj == nil and args.sing ~= nil then
args.adj = args.sing -- sing (singular) is apparently an old equivalent of adj
end
if args.adj == 'mid' then
Line 519 ⟶ 521:
end
end
if disp == 'x' then
args.joins = { args[i] or '', args[i+1] or '' }
elseif disp == 's' or disp == '/' then
args.disp = 'slash'
end
args.precision = args.precision or precision -- allow named parameter
if abbr == nil then
-- Default is to abbreviate output (use symbol), or input if flipped.
args.abbr = (disp == 'flip') and 'in' or 'out'
else
args.abbr_org = abbr -- original abbr (as entered by user)
if disp == 'flip' then -- 'in' = LHS, 'out' = RHS
if abbr == 'in' then
abbr = 'out'
elseif abbr == 'out' then
abbr = 'in'
end
end
args.abbr = abbr
end
return true, args, in_unit_table
end
local function default_precision(inclean, invalue, outvalue,
-- Return a default value for precision (an integer like 2, 0, -2).
-- Code follows procedures used in old template.
Line 534 ⟶ 554:
local log10 = math.log10
local prec, minprec, adjust
local
local fudge = 1e-14 -- {{Order of magnitude}} adds this, so we do too
-- Find fractional digits, handling cases like inclean = '12.345e6'.
local integer, dot, fraction = inclean:match('^(%d*)([' .. config.numdot .. ']?)(%d*)')
if utype == 'temperature' then
-- LATER: Give an error message if (invalue <
adjust = 0
local kelvin = (invalue -
if kelvin <= 0 then -- can get zero, or small but negative value due to precision problems
minprec = 2
Line 555 ⟶ 573:
return 0
end
if
-- More precision when output ft with integer input value.
adjust = -log10(
else
adjust = log10(math.abs(invalue / outvalue))
Line 577 ⟶ 595:
end
local function convert(value,
local inscale =
local outscale =
if
if
return 1 / (value * inscale * outscale)
end
return value * (inscale / outscale)
elseif
return (value -
else
return value * (inscale / outscale)
Line 592 ⟶ 610:
end
local function cvtround(
-- Return true,
-- show = rounded, formatted string from converting value in info,
-- using the rounding specified in parms.
-- singular = true if result is positive, and (after rounding)
-- is "1", or like "1.00"
-- or return true, nil if no value specified;
-- or return false, message if problem.
-- This code combines convert/round because some rounding requires
Line 605 ⟶ 622:
-- TODO Limit values to avoid abuse (for example, can currently set
-- precision to very large values like 999).
local
if info ~= nil then
invalue, inclean = info.value, info.clean
end
if invalue == nil or invalue == '' then
return true,
end
local outvalue = convert(invalue,
local isnegative
if outvalue < 0 then
Line 636 ⟶ 656:
show = string.format('%.0f', outvalue)
else
precision = default_precision(inclean, invalue, outvalue,
end
if precision then
Line 661 ⟶ 681:
end
end
-- TODO Does following work when exponent ~= nil?
-- What if show = '1000' and exponent = 1 (value = .1000*10^1 = 1)?
-- What if show = '1000' and exponent = 2 (value = .1000*10^2 = 10)?
if (show == '1' or show:match('^1%.0*$') ~= nil) and not isnegative then
-- Use match because on some systems 0.99999999999999999 is 1.0.
singular = true
end
return true, {
show = formatted,
is_scientific = is_scientific,
singular = singular,
clean = show, -- unformatted show (can be used to calculate rounded value)
exponent = exponent,
}
end
-- TODO Think about when to use ' ' and when to use ' '.
-- Old template always uses nbsp before a unit symbol, but seems inconsistent
-- before a unit name.
-- "Numbers less than 1,000 is not wrapped nor are unit symbols"
-- so 1000 is a threshold (use nbsp for smaller values), but no conclusive results.
-- Possibly a concern is wrapping when using {{convert}} in a table
-- (don't want to force a column to be unnecessarily wide by using nbsp).
local disp_joins = {
['or'] = { ' or ' , '' },
['sqbr-sp'] = { ' [' , ']' },
['
['
['
['
['slash-nosp'] = { '/' , '' },
['b'] = { ' (' , ')' },
}
Line 765 ⟶ 773:
-- evaluates 'v < 120' as a boolean with result
-- 'smallsuffix' if (value < 120), or 'bigsuffix' otherwise.
local
if
local msg = 'Unit "%s" has no default output unit.[[Category:Convert unknown unit]]'
return false, msg:format(unit_table.symbol)
end
if default:find('|', 1, true) == nil then
return true, default
end
local t = {}
default = default .. '|' -- to get last item
for item in default:gmatch('%s*(.-)%s*|') do
table.insert(t, item) -- split on '|', removing leading/trailing whitespace
end
if #t == 3 or #t == 4 then
local success, result = pcall(evaluate_condition, value, t[1])
if success then
default = result and t[2] or t[3]
if #t == 4 then
default = default .. t[4]
end
return true, default
end
end
local msg = 'Unit "%s" has an invalid default.[[Category:Convert unknown unit]]'
default = msg:format(unit_table.symbol)
return false, default
end
local function
-- Return
-- for value 1 or 2 (which), and 'in' or 'out' (unit_table.inout).
local abbr = parms.abbr
if abbr == 'values' then
return ''
end
local inout = unit_table.inout
local valinfo = unit_table.valinfo
local
local disp = parms.disp
local singular = valinfo[which].singular or (inout == 'in' and adj == 'on')
if unit_table.usename then
-- Old template does something like this.
if inout == 'in' then
if adj ~= 'on' and (abbr_org == 'out' or disp == 'flip') then
local value = valinfo[which].value
singular = (0 < value and value < 1.0001)
end
else
if (abbr_org == 'on') or
(disp == nil and (abbr_org == nil or abbr_org == 'out')) or
(disp == 'flip' and abbr_org == 'in') then
local clean, exponent = valinfo[which].clean, valinfo[which].exponent
local value = tonumber(clean) -- absolute value (any negative sign has been ignored)
if exponent ~= nil then
value = value * 10^exponent
end
singular = (value < 1.0001 and not valinfo[which].is_scientific)
end
end
end
local key_name = 'name2'
if singular then
key_name = 'name1'
end
if parms.sp == 'us' or unit_table.sp_us then
key_name = key_name .. '_us'
key_symbol = 'sym_us'
end
local id = unit_table[key_name]
if not unit_table.usename then
if ( abbr == 'on' or abbr == inout or (abbr == 'mos' and inout == 'out') or
(abbr_org == nil and unit_table.utype == 'temperature')) and not
end
end
if lk == 'on'
local link = link_exceptions[unit_table.symbol] or unit_table.link
if link ~= nil then
id = '[[' .. link .. '|' .. id .. ']]'
end
end
return id
end
local function process_input(parms, in_current)
-- Processing required once per conversion.
-- Return block of text to represent input (value/unit).
local id1 = make_id(parms, 1, in_current)
local
local disp = parms.disp
if disp == 'output only'
disp
parms.joins = { '', '' }
elseif disp == 'unit' then
if
else
end
parms.joins = { '', '' }
else
local range = parms.range
local id = (range == nil) and id1 or make_id(parms, 2, in_current)
if id ~= '' then
if adj == 'on' then
mos = false -- if hyphenated, suppress repeat of unit in a range
extra = '-' .. hyphenated(id) .. parms.mid
else
extra = ' ' .. id
end
end
local valinfo = in_current.valinfo
if range == nil then
result = valinfo[1].show
else
if mos then
result = valinfo[1].show .. ' ' .. id1 .. range[1] .. valinfo[2].show
else
result = valinfo[1].show .. range[1] .. valinfo[2].show
end
end
if disp == nil then -- special case the most common setting
parms.joins = disp_joins['b']
elseif disp ~= 'x' then
-- Old template does this.
if disp == 'slash' then
if parms.abbr_org == nil then
disp = 'slash-nbsp'
elseif abbr == 'in' or abbr == 'out' then
disp = 'slash-sp'
else
disp = 'slash-nosp'
end
elseif disp == 'sqbr' then
if abbr == 'on' then
disp = 'sqbr-nbsp'
else
disp = 'sqbr-sp'
end
end
parms.joins = disp_joins[disp] or disp_joins['b']
end
end
return result .. extra
end
local function process_one_output(parms, out_current)
-- Processing required for each output unit.
-- Return block of text to represent output (value/unit).
local id1 = make_id(parms, 1, out_current)
local extra = ''
local result
local disp = parms.disp
if disp == 'u2' or disp == 'unit2' then -- 'unit2' is not in old template
if parms.adj == 'on' then
result = hyphenated(id1)
else
result = id1
end
else
local range = parms.range
if not (disp == 'output number only' or disp == 'number') then
local id = (range == nil) and id1 or make_id(parms, 2, out_current)
if id ~= '' then
extra = ' ' .. id
end
end
local valinfo = out_current.valinfo
if range == nil then
result = valinfo[1].show
else
result = valinfo[1].show .. range[2] .. valinfo[2].show
end
end
return result .. extra
end
local function process(parms, in_unit_table)
-- Return true, s where s = final wikitext result (or false, message).
local info = in_unit_table.valinfo
local invalue1 = info[1].value
if parms.out_unit == nil then -- LATER need to catch empty string also?
local success, t = get_default(invalue1, in_unit_table)
if success then parms.out_unit = t else return false, t end
end
local out_unit_table
local success, t = units:lookup(parms.out_unit, parms.sp, true)
if success then out_unit_table = t else return false, t end
if in_unit_table.utype ~= out_unit_table.utype then
local msg = 'Cannot convert "%s" to "%s".[[Category:Convert dimension mismatch]]'
return false, msg:format(in_unit_table.utype, out_unit_table.utype)
end
local outputs = {}
local combos = out_unit_table.combination -- nil or table of unit tables
local imax = combos and #combos or 1 -- 1 (single unit) or number of unit tables
for i = 1, imax do
local success, info1, info2
local out_current = combos and combos[i] or out_unit_table
out_current.inout = 'out'
success, info1 = cvtround(parms, info[1], in_unit_table, out_current)
if not success then return false, info1 end
success, info2 = cvtround(parms, info[2], in_unit_table, out_current)
if not success then return false, info2 end
out_current.valinfo = { info1, info2 }
table.insert(outputs, process_one_output(parms, out_current))
end
local disp = parms.disp
local in_block = process_input(parms, in_unit_table)
local out_block = (disp == 'unit') and '' or table.concat(outputs, '; ')
if disp == 'flip' then
in_block, out_block = out_block, in_block
end
local wikitext = in_block .. parms.joins[1] .. out_block .. parms.joins[2]
if parms.sortable == 'on' then
wikitext = ntsh(
end
return true, wikitext
Line 932 ⟶ 1,003:
local p = {}
-- The following sets global variable 'mw' to simulate what Scribunto will do.
local bodge = require(is_test_run and "mw" or "Module:mw") -- fix up mw.text.tag
Line 939 ⟶ 1,009:
config = get_config(frame)
local pframe = frame:getParent()
local
local success, parms, in_unit_table = get_parms(pframe)
if success then
success, text = process(parms, in_unit_table)
else
text = parms
|