মডিউল:Convert: সংশোধিত সংস্করণের মধ্যে পার্থক্য

বিষয়বস্তু বিয়োগ হয়েছে বিষয়বস্তু যোগ হয়েছে
Johnuniq (আলোচনা | অবদান)
new version from en:Module:Convert; should be no visible change here
Johnuniq (আলোচনা | অবদান)
new version from en:Module:Convert
১ নং লাইন:
-- Convert a value from one unit of measurement to another.
-- Example: {{convert|123|lb|kg}} --> 123 pounds (56 kg)
-- See [[:en:Template:Convert/Transwiki guide]] if copying to another wiki.
 
local MINUS = '−' -- Unicode U+2212 MINUS SIGN (UTF-8: e2 88 92)
৯ ⟶ ১০ নং লাইন:
local ustring = mw.ustring
local ulen = ustring.len
local usub = ustring.sub
 
-- mw.ustring has two bugs: following works around one of them; see "2013-07-05" for second.
-- Bug has been reported, and the fix will be deployed, possibly before August 2013.
-- local usub = ustring.sub
-- When fix is deployed, remove following usub function, and uncomment above usub variable.
local function usub(s, i, j)
return (j and i > j) and '' or ustring.sub(s, i, j)
end
 
-- Configuration options to keep magic values in one location.
-- The conversionConversion data and message text are defined in separate modules.
local config, maxsigfig
local numdot, numsep -- each must be a single byte for simple regex search/replace
local numdot -- must be '.' or ',' or a character which works in a regex as used here
local maxsigfig, warnings
local numsep, numsep_remove
local default_exceptions, link_exceptions, all_units
local text_code
local SIprefixes, all_categories, all_messages, customary_units, disp_joins
local varname -- can be a code to use variable names that depend on value
local en_option_name, en_option_value, eng_scales, range_aliases, range_types
local from_en_table -- to translate an output string of en digits to local language
local to_en_table -- to translate an input string of digits in local language to en
-- Use translation_table in convert/text to change the following.
local group_method = 3 -- code for how many digits are in a group
local per_word = 'per' -- for units like "liters per kilometer"
local plural_suffix = 's' -- only other useful value is probably '' to disable plural unit names
local from_en_table -- to translate an output string of en digits to local language
local to_en_table -- to translate an input string of digits in local language to en
 
-- All units should be defined in the data module. However, to cater for quick changes
৩৬ ⟶ ৩৩ নং লাইন:
local extra_module -- name of module with extra units
local extra_units -- nil or table of extra units from extra_module
 
local function boolean(text)
-- Return true if text represents a "true" option value.
if text then
text = text:lower()
if text == '1' or text == 'y' or text == 'yes' or text == 'on' or text == 'true' then
return true
end
end
end
 
local function from_en(text)
-- Input is a string representing a number in en digits with '.' decimal mark,
-- without digit grouping (which is done just after calling this).
-- Return the translation of the string with numdot and digits in local language.
if numdot ~= '.' then
text = text:gsub('%.', numdot)
end
if from_en_table then
text = text:gsub('%d', from_en_table)
end
return text
end
 
local function to_en(text)
-- Input is a string representing a number in the local language with
-- an optional numdot decimal mark and numsep digit grouping.
-- Return the translation of the string with '.' mark and en digits,
-- and no separators (they have to be removed here to handle cases like
-- numsep = '.' and numdot = ',' with input "1.234.567,8").
if numsepnumsep_remove ~= '' then
text = text:gsub('[' .. numsep .. ']'numsep_remove, '') -- use '[x]' in case x is '.'
end
if numdot ~= '.' then
text = text:gsub('[' .. numdot .. ']', '.')
end
if to_en_table then
text = ustring.gsub(text, '%d', to_en_table)
end
return text
end
 
৮২ ⟶ ৬৯ নং লাইন:
 
local function set_config(frame)
-- Set configuration options from template #invoke or defaults.
local args config = frame.args
maxsigfig = config.maxsigfig or 14 -- maximum number of significant figures
numdot = args.numdot or '.' -- decimal mark before fractional digits
-- Scribunto sets the global variable 'mw'.
numsep = args.numsep or ',' -- group separator for numbers (',', '.', '')
-- A testing program can set the global variable 'is_test_run'.
maxsigfig = args.maxsigfig or 14 -- maximum number of significant figures
local data_module, text_module, data_code
warnings = boolean(args.warnings) -- true if want warnings for invalid options
if is_test_run then
-- Scribunto sets the global variable 'mw'.
local langcode = mw.language.getContentLanguage().code
-- A testing program can set the global variable 'is_test_run'.
data_module = "convertdata-" .. langcode
local data_module, text_module, data_code, text_code
text_module = "converttext-" .. langcode
if is_test_run then
extra_module = "convertextra-" .. langcode
local langcode = mw.language.getContentLanguage().code
spell_module = "ConvertNumeric"
data_module = "convertdata-" .. langcode
else
text_module = "converttext-" .. langcode
local sandbox = config.sandbox and ('/' .. config.sandbox) or ''
extra_module = "convertextra"
data_module = "Module:Convert/data" .. sandbox
spell_module = "ConvertNumeric"
text_module = "Module:Convert/text" .. sandbox
else
data_module extra_module = "Module:Convert/dataextra" .. sandbox
text_module spell_module = "Module:Convert/textConvertNumeric"
end
extra_module = "Module:Convert/extra"
data_code = mw.loadData(data_module)
spell_module = "Module:ConvertNumeric"
text_code = mw.loadData(text_module)
end
default_exceptions = data_code = mw.loadData(data_module)default_exceptions
link_exceptions = data_code.link_exceptions
text_code = mw.loadData(text_module)
default_exceptions all_units = data_code.default_exceptionsall_units
local translation = text_code.translation_table
link_exceptions = data_code.link_exceptions
if translation then
all_units = data_code.all_units
numdot = translation.numdot
SIprefixes = text_code.SIprefixes
numsep = translation.numsep
all_categories = text_code.all_categories
if translation.group then
all_messages = text_code.all_messages
group_method = translation.group
customary_units = text_code.customary_units
end
disp_joins = text_code.disp_joins
if translation.per_word then
en_option_name = text_code.en_option_name
per_word = translation.per_word
en_option_value = text_code.en_option_value
end
eng_scales = text_code.eng_scales
if translation.plural_suffix then
range_aliases = text_code.range_aliases
plural_suffix = translation.plural_suffix
range_types = text_code.range_types
end
local translation = text_code.translation_table
varname if= translation then.varname
from_en_table if= translation.group thenfrom_en
local use_workaround = true
group_method = translation.group
if use_workaround then
end
-- 2013-07-05 workaround bug by making a copy of the required table.
if translation.plural_suffix then
-- mw.ustring.gsub fails with a table (to_en_table) as the replacement,
plural_suffix = translation.plural_suffix
-- if the table is accessed via mw.loadData.
end
local from_en_tablesource = translation.from_ento_en
if source then
local use_workaround = true
to_en_table = {}
if use_workaround then
for k, v in pairs(source) do
-- 2013-07-05 workaround bug by making a copy of the required table.
to_en_table[k] = v
-- mw.ustring.gsub fails with a table (to_en_table) as the replacement,
end
-- if the table is accessed via mw.loadData.
end
local source = translation.to_en
else
if source then
to_en_table = {}translation.to_en
end
for k, v in pairs(source) do
end
to_en_table[k] = v
numdot = config.numdot or numdot or '.' -- decimal mark before fractional digits
end
numsep = config.numsep or numsep or ',' -- group separator for numbers
end
-- numsep should be ',' or '.' or '' or ' ' or a Unicode character.
else
-- numsep_remove must work in a regex to identify separators to be removed.
to_en_table = translation.to_en
numsep_remove = (numsep == '.') and '%.' or numsep
end
end
end
 
local function collection()
-- Return a table to hold items.
return {
n = 0,
add = function (self, item)
self.n = self.n + 1
self[self.n] = item
end,
}
}
end
 
local function divide(numerator, denominator)
-- Return integers quotient, remainder resulting from dividing the two
-- given numbers, which should be unsigned integers.
local quotient, remainder = floor(numerator / denominator), numerator % denominator
if not (0 <= remainder and remainder < denominator) then
-- Floating point limits may need this, as in {{convert|160.02|Ym|ydftin}}.
remainder = 0
end
return quotient, remainder
end
 
local function split(text, delimiter)
-- Return a numbered table with fields from splitting text.
-- The delimiter is used in a regex without escaping (for example, '.' would fail).
-- Each field has any leading/trailing whitespace removed.
local t = {}
text = text .. delimiter -- to get last item
for item in text:gmatch('%s*(.-)%s*' .. delimiter) do
table.insert(t, item)
end
return t
end
 
local function strip(text)
-- If text is a string, return its content with no leading/trailing
-- whitespace. Otherwise return nil (a nil argument gives a nil result).
if type(text) == 'string' then
return text:match("^%s*(.-)%s*$")
end
end
 
local function wanted_category(cat)
-- Return cat if it is wanted in current namespace, otherwise return nil.
-- This is so tracking categories only include pages that need correction.
local title = mw.title.getCurrentTitle()
if title then
local nsdefault = '0' -- default namespace: '0' = article; '0,10' = article and template
local namespace = title.namespace
for _, v in ipairs(split(config.nscat or nsdefault, ',')) do
if namespace == tonumber(v) then
return cat
end
end
end
end
 
local function message(mcode)
-- Return wikitext for an error message, including category if specified
-- for the message type.
-- mcode = numbered table specifying the message:
-- mcode[1] = 'cvt_xxx' (string used as a key to get message info)
-- mcode[2] = 'parm1' (string to replace first %s if any in message)
-- mcode[3] = 'parm2' (string to replace second %s if any in message)
-- mcode[4] = 'parm3' (string to replace third %s if any in message)
local msg = text_code.all_messages[mcode[1]]
local nowiki = mw.text.nowiki
if msg then
if msg then
local text = format(msg[1] or 'Missing message',
local parts = {}
mcode[2] or '?',
local regex, replace = msg.regex, msg.replace
mcode[3] or '?',
for i = 1, 3 do
mcode[4] or '?')
local limit = 40
local cat = all_categories[msg[2]] or ''
local s = mcode[i + 1]
local prefix = all_messages[msg.warning and 'cvt_prefix_warning' or 'cvt_prefix_error'] or ''
if s then
local suffix = (prefix == '') and '' or '</span>'
if regex and replace then
local regex, replace = msg.regex, msg.replace
s = if s:gsub(regex and, replace then)
limit = nil -- allow long "should be" messages
text = text:gsub(regex, replace)
end
-- Escape user input so it does not break the message.
return prefix .. ' ' .. text .. cat .. suffix
-- To avoid reference tags (like {{convert|1<ref>xyz</ref>|m}}) or other tags
end
-- breaking the mouseover title, any strip marker starting with char(127) is
return 'Convert internal error: unknown message'
-- replaced with escaped '<ref>...</ref>' or '...' (text not needing i18n).
local append = ''
local pos = s:find(string.char(127), 1, true)
if pos then
if s:find('-ref-', 1, true) then
append = '&lt;ref&gt;...&lt;/ref&gt;'
else
append = '...'
end
s = s:sub(1, pos - 1)
end
if limit and ulen(s) > limit then
s = usub(s, 1, limit)
if append == '' then
append = '...'
end
end
s = nowiki(s) .. append
else
s = '?'
end
parts[i] = s
end
local title = format(msg[1] or 'Missing message', parts[1], parts[2], parts[3])
local text = msg[2] or 'Missing message'
local cat = wanted_category(text_code.all_categories[msg[3]]) or ''
local anchor = msg[4] or ''
local fmt = text_code.all_messages['cvt_format'] or 'convert: bug'
title = title:gsub('"', '&quot;')
return format(fmt, anchor, title, text, cat)
end
return 'Convert internal error: unknown message'
end
 
local function add_warning(parms, level, mcode, text)
-- If enabled, add a warning that will be displayed after the convert result.
-- To reduce output noise, only the first warning is displayed.
if config.warnings then
if level <= if parms(tonumber(config.warnings) ==or nil1) then
if parms.warnings == message({ mcode, textnil })then
parms.warnings = message({ mcode, text })
end
end
end
end
end
 
local function spell_number(parms, inout, number, numerator, denominator)
-- Return result of spelling (number, numerator, denominator), or
-- return nil if spelling is not available or not supported for given text.
-- Examples (each value must be a string or nil):
-- Input should use one of these forms:
-- number numerator denominator example output
-- ------ --------- ----------- -------------------
-- string"1.23" nil nil one point two three
-- "1" -- "2" string string "3" string one and two thirds
-- --nil nil "2" string "3" string two thirds
if not speller then
local function get_speller(module)
return require(module).spell_number
end
local success
success, speller = pcall(get_speller, spell_module)
if not success or type(speller) ~= 'function' then
add_warning(parms, 1, 'cvt_spell_unavailablecvt_no_spell')
return nil
end
end
local case = parms.opt_spell_upper
if parms.spell_upper == inout then
parms.opt_spell_upper = nil -- only uppercase first number in a multiple unit
case = true
local sp = not parms.opt_sp_us
parms.spell_upper = nil -- only uppercase first word in a multiple unit
local adj = parms.opt_adjectival
end
return speller(number, numerator, denominator, case, sp, adj)
local sp = not parms.opt_sp_us
local adj = parms.opt_adjectival
return speller(number, numerator, denominator, case, sp, adj)
end
 
২৪৩ ⟶ ২৯২ নং লাইন:
-- LATER: If need much more code, move to another module to simplify this module.
local function speed_of_sound(altitude)
-- This is for the Mach built-in unit of speed.
-- Return speed of sound in metres per second at given altitude in feet.
-- If no altitude given, use default (zero altitude = sea level).
-- Table gives speed of sound in miles per hour at various altitudes:
-- altitude = -17,499 to 302,499 feet
-- mach_table[a + 4] = s where
-- a = (altitude / 5000) rounded to nearest integer (-3 to 60)
-- s = speed of sound (mph) at that altitude
-- LATER: Should calculate result from an interpolation between the next
-- lower and higher altitudes in table, rather than rounding to nearest.
-- From: http://www.aerospaceweb.org/question/atmosphere/q0112.shtml
local mach_table = { -- a =
799.5, 787.0, 774.2, 761.207051, -- -3 to 0
748.0, 734.6, 721.0, 707.0, 692.8, 678.3, 663.5, 660.1, 660.1, 660.1, -- 1 to 10
660.1, 660.1, 660.1, 662.0, 664.3, 666.5, 668.9, 671.1, 673.4, 675.6, -- 11 to 20
677.9, 683.7, 689.9, 696.0, 702.1, 708.1, 714.0, 719.9, 725.8, 731.6, -- 21 to 30
737.3, 737.7, 737.7, 736.2, 730.5, 724.6, 718.8, 712.9, 707.0, 701.1, -- 31 to 40
695.0, 688.9, 682.8, 676.6, 670.4, 664.1, 657.8, 652.9, 648.3, 643.7, -- 41 to 50
639.1, 634.4, 629.6, 624.8, 620.0, 615.2, 613.2, 613.2, 613.2, 613.5, -- 51 to 60
}
}
altitude = altitude or 0
local a = (altitude < 0) and -altitude or altitude
a = floor(a / 5000 + 0.5)
if altitude < 0 then
a = -a
end
if a < -3 then
a = -3
elseif a > 60 then
a = 60
end
return mach_table[a + 4] * 0.44704 -- mph converted to m/s
end
-- END: Code required only for built-in units.
------------------------------------------------------------------------
 
local function get_range(word)
-- Return a range (string or table) corresponding to word (like "to"),
-- or return nil if not a range word.
local ranges = text_code.ranges
return ranges.types[word] or ranges.types[ranges.aliases[word]]
end
 
local function check_mismatch(unit1, unit2)
-- If unit1 cannot be converted to unit2, return an error message table.
-- This allows conversion between units of the same type, and between
-- Nm (normally torque) and ftlb (energy), as in gun-related articles.
-- This works because Nm is the base unit (scale = 1) for both the
-- primary type (torque), and the alternate type (energy, where Nm = J).
-- A match occurs if the primary types are the same, or if unit1 matches
-- the alternate type of unit2, and vice versa. That provides a whitelist
-- of which conversions are permitted between normally incompatible types.
if unit1.utype == unit2.utype or
(unit1.utype == unit2.alttype and unit1.alttype == unit2.utype) then
return nil
end
return { 'cvt_mismatch', unit1.utype, unit2.utype }
end
 
local function override_from(out_table, in_table, fields)
-- Copy the specified fields from in_table to out_table, but do not
-- copy nil fields (keep any corresponding field in out_table).
for _, field in ipairs(fields) do
if in_table[field] then
out_table[field] = in_table[field]
end
end
end
 
local function shallow_copy(t)
-- Return a shallow copy of table t.
-- Do not need the features and overhead of the Scribunto mw.clone().
local result = {}
for k, v in pairs(t) do
result[k] = v
end
return result
end
 
local unit_mt = {
-- Metatable to get missing values for a unit that does not accept SI prefixes,.
-- Warning: The boolean value 'false' is returned for any missing field
-- or for a unit that accepts prefixes but where no prefix was used.
-- so __index is not called twice for the same field in a given unit.
-- In the latter case, and before use, fields symbol, name1, name1_us
__index = function (self, key)
-- must be set from _symbol, _name1, _name1_us respectively.
local value
__index = function (self, key)
if key == 'name1' or key == 'sym_us' then
local value
value = self.symbol
if key == 'name1' or key == 'sym_us' then
elseif key == 'name2' then
value = self.symbol
value = self.name1 .. plural_suffix
elseif key == 'name2' then
elseif key == 'name1_us' then
value = self.name1 .. plural_suffix
value = self.name1
elseif key == 'name1_us' then
if not rawget(self, 'name2_us') then
value = self.name1
-- If name1_us is 'foot', do not make name2_us by appending plural_suffix.
if not rawget(self, 'name2_us') then
self.name2_us = self.name2
-- If name1_us is 'foot', do not make name2_us by appending plural_suffix.
end
self.name2_us = self.name2
elseif key == 'name2_us' then
end
local raw1_us = rawget(self, 'name1_us')
elseif key == 'name2_us' then
if raw1_us then
local raw1_us = rawget(self, 'name1_us')
value = raw1_us .. plural_suffix
if raw1_us then
else
value = raw1_us .. plural_suffix
value = self.name2
else
end
value = self.name2
elseif key == 'link' then
end
value = self.name1
elseif key == 'link' then
else
value = self.name1
value = false
elseif key == 'builtin' then
end
value = false
rawset(self, key, value)
else
return nilvalue
end
rawset(self, key, value)
return value
end
}
 
local function prefixed_name(unit, name, index)
-- Return unit name with SI prefix inserted at correct position.
-- index = 1 (name1), 2 (name2), 3 (name1_us), 4 (name2_us).
-- The position is a byte (not character) index, so use Lua's sub().
local pos = rawget(unit, 'prefix_position')
if type(pos) == 'string' then
pos = tonumber(split(pos, ',')[index])
end
if pos then
return name:sub(1, pos - 1) .. unit.si_name .. name:sub(pos)
end
return unit.si_name .. name
end
 
local unit_prefixed_mt = {
-- Metatable to get missing values for a unit that accepts SI prefixes,.
-- Before use, fields si_name, si_prefix must be defined.
-- and where a prefix has been used.
-- The unit must define _symbol, _name1 and
-- Before use, fields si_name, si_prefix must be defined.
-- may define _sym_us, _name1_us, _name2_us
__index = function (self, key)
-- (_sym_us, _name2_us may be defined for a language using sp=us
local value
-- to refer to a variant unrelated to U.S. units).
if key == 'symbol' then
__index = function (self, key)
value = self.si_prefix .. self._symbol
local value
elseif key == 'sym_us' then
if key == 'symbol' then
value = self.symbol -- always the same as sym_us for prefixed units
value = self.si_prefix .. self._symbol
elseif key == 'name1' then
elseif key == 'sym_us' then
local pos = rawget(self, 'prefix_position') or 1
value = rawget(self._name1, '_sym_us')
if value then
value = usub(value, 1, pos - 1) .. self.si_name .. usub(value, pos)
value = self.si_prefix .. value
elseif key == 'name2' then
else
value = self.name1 .. plural_suffix
value = self.symbol
elseif key == 'name1_us' then
end
value = rawget(self, '_name1_us')
elseif key == if value'name1' then
value = prefixed_name(self, self._name1, 1)
local pos = rawget(self, 'prefix_position') or 1
elseif key == 'name2' then
value = usub(value, 1, pos - 1) .. self.si_name .. usub(value, pos)
value = rawget(self, '_name2')
else
if value = self.name1then
value = prefixed_name(self, value, 2)
end
else
elseif key == 'name2_us' then
value = self.name1 .. plural_suffix
if rawget(self, '_name1_us') then
end
value = self.name1_us .. plural_suffix
elseif key == 'name1_us' then
else
value = rawget(self.name2, '_name1_us')
if value then
end
value = prefixed_name(self, value, 3)
elseif key == 'link' then
else
value = self.name1
value = self.name1
elseif key == 'builtin' then
end
value = false
elseif key == 'name2_us' then
else
value = rawget(self, '_name2_us')
return nil
if value then
end
value = rawsetprefixed_name(self, keyvalue, value4)
elseif rawget(self, '_name1_us') then
return value
value = self.name1_us .. plural_suffix
end
else
value = self.name2
end
elseif key == 'link' then
value = self.name1
else
value = false
end
rawset(self, key, value)
return value
end
}
 
local unit_per_mt = {
-- Metatable to get values for a "per" unit of form "x/y".
-- This is never called to determine a unit name or link because "per" units
-- are handled as a special case.
__index = function (self, key)
local value
if key == 'symbol' then
local per = self.per
local unit1, unit2 = per[1], per[2]
if unit1 then
value = unit1[key] .. '/' .. unit2[key]
else
value = '/' .. unit2[key]
end
end
elseif key == 'sym_us' then
value = self.symbol
elseif key == 'scale' then
local per = self.per
local unit1, unit2 = per[1], per[2]
value = (unit1 and unit1.scale or 1) * self.scalemultiplier / unit2.scale
else
elseif key == 'builtin' then
value = false
end
else
rawset(self, key, value)
return nil
return value
end
end
rawset(self, key, value)
return value
end
}
 
local function lookup(unitcode, opt_sp_us, what, utable, fails, depth)
-- Return true, t where t is a copy of the unit's converter table,
-- or return false, t where t is an error message table.
-- Parameter opt_sp_us is true for US spelling of SI prefixes and
-- the symbol and name of the unit. If true, the result includes field
-- sp_us = true (that field may also have been in the unit definition).
-- Parameter 'what' determines whether combination units are accepted:
-- 'no_combination' : single unit only
-- 'any_combination' : single unit or combination or output multiple
-- 'only_multiple' : single unit or output multiple only
-- Parameter unitcode is a symbol (like 'g'), with an optional SI prefix (like 'kg').
-- If, for example, 'kg' is in this table, that entry is used;
-- otherwise the prefix ('k') is applied to the base unit ('g').
-- If unitcode is a known combination code (and if allowed by what),
-- a table of output multiple unit tables is included in the result.
-- For compatibility with the old template, underscoresan underscore in unitcodea areunitcode replacedis
-- replaced with spacesa space so usage like {{convert|350|board_feet}} --> 350 board feet (0.83 m³)works.
-- Wikignomes may also put two spaces or "&nbsp;" in combinations, so
utable = utable or all_units
-- replace underscore, "&nbsp;", and multiple spaces with a single space.
fails = fails or {}
utable = utable or all_units
depth = depth and depth + 1 or 1
fails = fails or {}
if depth > 9 then
depth = depth and depth + 1 or 1
-- There are ways to mistakenly define units which result in infinite
if depth > 9 then
-- recursion when lookup() is called. That gives a long delay and very
-- There are ways to mistakenly define units which result in infinite
-- confusing error messages, so the depth parameter is used as a guard.
-- recursion when lookup() is called. That gives a long delay and very
return false, { 'cvt_lookup', unitcode }
-- confusing error messages, so the depth parameter is used as a guard.
end
return false, { 'cvt_lookup', unitcode }
if unitcode == nil or unitcode == '' then
end
return false, { 'cvt_no_unit' }
if unitcode == nil or unitcode == '' then
end
return false, { 'cvt_no_unit' }
unitcode = unitcode:gsub('_', ' ')
end
local t = utable[unitcode]
unitcode = unitcode:gsub('_', ' '):gsub('&nbsp;', ' '):gsub(' +', ' ')
if t then
local t = utable[unitcode]
if t.shouldbe then
if t then
return false, { 'cvt_should_be', t.shouldbe }
if t.shouldbe then
end
return false, { 'cvt_should_be', t.shouldbe }
local force_sp_us = opt_sp_us
end
if t.sp_us then
local force_sp_us = trueopt_sp_us
if t.sp_us then
opt_sp_us = true
force_sp_us = true
end
opt_sp_us = true
local target = t.target -- nil, or unitcode is an alias for this target
end
if target then
local target = t.target -- nil, or unitcode is an alias for this target
local success, result = lookup(target, opt_sp_us, what, utable, fails, depth)
if target then
if not success then return false, result end
local success, result = lookup(target, opt_sp_us, what, utable, fails, depth)
override_from(result, t, { 'customary', 'default', 'link', 'symbol', 'symlink' })
if not success then return false, result end
local multiplier = t.multiplier
override_from(result, t, { 'customary', 'default', 'link', 'symbol', 'symlink' })
if multiplier then
local result.multiplier = tostring(t.multiplier)
if multiplier then
result.scale = result.scale * multiplier
result.multiplier = tostring(multiplier)
end
result.scale = result.scale * multiplier
return true, result
end
return true, result
local per = t.per -- nil/false, or a numbered table for "x/y" units
end
if per then
local per = t.per -- nil/false, or a numbered table for "x/y" units
local result = { utype = t.utype, per = {} }
if per then
override_from(result, t, { 'default', 'invert', 'iscomplex', 'symbol', 'symlink' })
local result = { utype = t.utype, per = {} }
result.symbol_raw = (result.symbol or false) -- to distinguish between a defined exception and a metatable calculation
result.scalemultiplier = t.multiplier or 1
local cvt = result.per
override_from(result, t, { 'invert', 'iscomplex', 'default', 'link', 'symbol', 'symlink' })
local prefix
result.symbol_raw = (result.symbol or false) -- to distinguish between a defined exception and a metatable calculation
for i, v in ipairs(per) do
local cvt = result.per
if i == 1 and (v == '$' or v == '£') then
local prefix = v
for i, v in ipairs(per) do
else
if i == 1 and text_code.currency[v] then
local success, t = lookup(v, opt_sp_us, 'no_combination', utable, fails, depth)
prefix = v
if not success then return false, t end
else
cvt[i] = t
local success, t = lookup(v, opt_sp_us, 'no_combination', utable, fails, depth)
if t.sp_us then -- if the top or bottom unit forces sp=us, set the per unit to use the correct name/symbol
if not success then return false, t end
force_sp_us = true
cvt[i] = t
end
if t.sp_us then -- if the top or bottom unit forces sp=us, set the per unit to use the correct name/symbol
end
force_sp_us = true
end
end
if prefix then
end
result.vprefix = prefix
end
else
if prefix then
result.vprefix = false -- to avoid calling __index
result.vprefix = prefix
end
else
result.sp_us = force_sp_us
result.vprefix = false -- to avoid calling __index
return true, setmetatable(result, unit_per_mt)
end
result.sp_us = force_sp_us
local combo = t.combination -- nil or a table of unitcodes
return true, setmetatable(result, unit_per_mt)
if combo then
end
local multiple = t.multiple
local combo = t.combination -- nil or a table of unitcodes
if what == 'no_combination' or (what == 'only_multiple' and multiple == nil) then
if combo then
return false, { 'cvt_bad_unit', unitcode }
local multiple = t.multiple
end
if what == 'no_combination' or (what == 'only_multiple' and not multiple) then
-- Recursively create a combination table containing the
return false, { 'cvt_bad_unit', unitcode }
-- converter table of each unitcode.
end
local result = { utype = t.utype, multiple = multiple, combination = {} }
-- Recursively create a combination table containing the
local cvt = result.combination
-- converter table of each unitcode.
for i, v in ipairs(combo) do
local result = { utype = t.utype, multiple = multiple, combination = {} }
local success, t = lookup(v, opt_sp_us, multiple and 'no_combination' or 'only_multiple', utable, fails, depth)
local cvt = result.combination
if not success then return false, t end
for i, v in ipairs(combo) do
cvt[i] = t
local success, t = lookup(v, opt_sp_us, multiple and 'no_combination' or 'only_multiple', utable, fails, depth)
end
if not success then return truefalse, resultt end
cvt[i] = t
end
end
local result = shallow_copy(t)
return true, result
result.sp_us = force_sp_us
end
if result.prefixes then
local result.symbol = result._symbolshallow_copy(t)
result.name1sp_us = result._name1force_sp_us
if result.prefixes then
result.name1_us = result._name1_us
result.si_name = ''
end
result.si_prefix = ''
return true, setmetatable(result, unit_mt)
return true, setmetatable(result, unit_prefixed_mt)
end
end
for plen = SIprefixes[1] or 2, 1, -1 do
return true, setmetatable(result, unit_mt)
-- Look for an SI prefix; should never occur with an alias.
end
-- Check for longer prefix first ('dam' is decametre).
local SIprefixes = text_code.SIprefixes
-- SIprefixes[1] = prefix maximum #characters (as seen by mw.ustring.sub).
for plen = SIprefixes[1] or 2, 1, -1 do
local prefix = usub(unitcode, 1, plen)
-- Look for an SI prefix; should never occur with an alias.
local si = SIprefixes[prefix]
-- Check for longer prefix first ('dam' is decametre).
if si then
-- SIprefixes[1] = prefix maximum #characters (as seen by mw.ustring.sub).
local t = utable[usub(unitcode, plen+1)]
local prefix = usub(unitcode, 1, plen)
if t and t.prefixes then
local si = SIprefixes[prefix]
local result = shallow_copy(t)
if opt_sp_ussi then
local t = utable[usub(unitcode, plen+1)]
result.sp_us = true
if t and t.prefixes then
end
local result = shallow_copy(t)
if result.sp_us and si.name_us then
if opt_sp_us then
result.si_name = si.name_us
result.sp_us = true
else
end
result.si_name = si.name
if result.sp_us and si.name_us then
end
result.si_prefixsi_name = si.prefix or prefixname_us
else
result.scale = t.scale * 10 ^ (si.exponent * t.prefixes)
result.si_name = si.name
return true, setmetatable(result, unit_prefixed_mt)
end
end
result.si_prefix = si.prefix or prefix
end
result.scale = t.scale * 10 ^ (si.exponent * t.prefixes)
end
return true, setmetatable(result, unit_prefixed_mt)
-- Accept any unit with an engineering notation prefix like "e6cuft"
end
-- (million cubic feet), but not chained prefixes like "e3e6cuft",
end
-- and not if the unit is a combination or multiple,
end
-- and not if the unit has an offset or is a built-in.
-- Accept any unit with an engineering notation prefix like "e6cuft"
-- Only en digits are accepted.
-- (million cubic feet), but not chained prefixes like "e3e6cuft",
local exponent, baseunit = unitcode:match('^e(%d+)(.*)')
-- and not if the unit is a combination or multiple,
if exponent then
-- and not if the unit has an offset or is a built-in.
local engscale = eng_scales[exponent]
-- Only en digits are accepted.
if engscale then
local has_plus = unitcode:find('+', 1, true)
local success, result = lookup(baseunit, opt_sp_us, 'no_combination', utable, fails, depth)
if not successhas_plus then return false, result end
local exponent, baseunit = unitcode:match('^e(%d+)(.*)')
if not (result.offset or result.builtin or result.engscale) then
if exponent then
result.defkey = unitcode -- key to lookup default exception
local engscale = text_code.eng_scales[exponent]
result.engscale = engscale
if engscale then
result.scale = result.scale * 10 ^ tonumber(exponent)
local success, result = lookup(baseunit, opt_sp_us, 'no_combination', utable, fails, depth)
return true, result
if not success then return false, result end
if not (result.offset or result.builtin or result.engscale) then
end
result.defkey = unitcode -- key to lookup default exception
end
result.engscale = engscale
if not extra_units then
result.scale = result.scale * 10 ^ tonumber(exponent)
local success, extra = pcall(function () return require(extra_module).extra_units end)
return true, result
if success and type(extra) == 'table' then
end
extra_units = extra
end
end
end
if extra_units then
-- Accept user-defined combinations like "acre+m2+ha" or "acre m2 ha" for output.
-- A unit in one data table might refer to a unit in the other table, so
-- If '+' is used, each unit code can include a space, and any error is fatal.
-- switch between them, relying on fails or depth to terminate loops.
-- If ' ' is used and if each space-separated word is a unit code, it is a combo,
local failed = fails[unitcode]
-- but errors are not fatal so the unit code can be looked up as an extra unit.
if not failed then
local err_is_fatal
fails[unitcode] = true
local combo = collection()
local other = (utable == all_units) and extra_units or all_units
if has_plus then
local success, result = lookup(unitcode, opt_sp_us, what, other, fails, depth)
err_is_fatal = true
if success then
for item in (unitcode .. '+'):gmatch('%s*(.-)%s*%+') do
return true, result
if item ~= '' then
end
combo:add(item)
end
end
end
return false, { 'cvt_unknown', unitcode }
elseif unitcode:find('%s') then
for item in unitcode:gmatch('%S+') do
combo:add(item)
end
end
if combo.n > 1 then
local function lookup_combo()
if what == 'no_combination' or what == 'only_multiple' then
return false, { 'cvt_bad_unit', unitcode }
end
local result = { combination = {} }
local cvt = result.combination
for i, v in ipairs(combo) do
local success, t = lookup(v, opt_sp_us, 'only_multiple', utable, fails, depth)
if not success then return false, t end
if i == 1 then
result.utype = t.utype
else
local mismatch = check_mismatch(result, t)
if mismatch then
return false, mismatch
end
end
cvt[i] = t
end
return true, result
end
local success, result = lookup_combo()
if success or err_is_fatal then
return success, result
end
end
if not get_range(unitcode) then -- do not require extra if looking up a range word which cannot be a unit
if not extra_units then
local success, extra = pcall(function () return require(extra_module).extra_units end)
if success and type(extra) == 'table' then
extra_units = extra
end
end
if extra_units then
-- A unit in one data table might refer to a unit in the other table, so
-- switch between them, relying on fails or depth to terminate loops.
if not fails[unitcode] then
fails[unitcode] = true
local other = (utable == all_units) and extra_units or all_units
local success, result = lookup(unitcode, opt_sp_us, what, other, fails, depth)
if success then
return true, result
end
end
end
end
if to_en_table then
-- At fawiki it is common to translate all digits so a unit like "km2" becomes "km۲".
local en_code = ustring.gsub(unitcode, '%d', to_en_table)
if en_code ~= unitcode then
return lookup(en_code, opt_sp_us, what, utable, fails, depth)
end
end
return false, { 'cvt_unknown', unitcode }
end
 
local function valid_number(num)
-- Return true if num is a valid number.
-- In Scribunto (different from some standard Lua), when expressed as a string,
-- Expressed as a string, overflow or other problems are indicated with
-- overflow or other problems are indicated with text like "inf" or "nan"
-- text like "1.#INF" or ".#IND" which are regarded as invalid here.
-- which are regarded as invalid here (each contains "n").
if type(num) == 'number' and tostring(num):find('#', 1, true) == nil then
if type(num) == 'number' and tostring(num):find('n', 1, true) == nil then
return true
return true
end
end
end
 
local function ntsh(num, debug)
-- Return html text to be used for a hidden sort key so that
-- the given number will be sorted in numeric order.
-- If debug == true, output is in a box (not hidden).
-- This implements Template:Ntsh (number table sorting, hidden).
local result, style
if not valid_number(num) then
if num < 0 then
result = '1000000000000000000'
else
result = '9000000000000000000'
end
elseif num == 0 then
result = '5000000000000000000'
else
local mag = floor(log10(abs(num)) + 1e-14)
local prefix
if num > 0 then
prefix = 7000 + mag
else
prefix = 2999 - mag
num = num + 10^(mag+1)
end
result = format('%d', prefix) .. format('%015.0f', floor(num * 10^(14-mag)))
end
if debug then
style = 'border:1px solid'
else
style = 'display:none'
end
return '<span style="' .. style .. '">' .. result .. '</span>'
end
 
local function hyphenated(name, parts)
-- Return a hyphenated form of given name (for adjectival usage).
-- The name may be linked and the target of the link must not be changed.
-- This uses a simple and efficient procedure that works for most cases.
-- Hypothetical examples:
-- Some units (if used) would require more, and can later think about
-- [[long ton|ton]] → [[long ton|ton]] (no change)
-- adding a method to handle exceptions.
-- [[tonne|long ton]] → [[tonne|long-ton]]
-- The procedure is to replace each space with a hyphen, but
-- [[metric ton|long ton]] → [[metric ton|long-ton]]
-- not a space after ')' [for "(pre-1954&nbsp;US) nautical mile"], and
-- [[long ton]] → [[long ton|long-ton]]
-- not spaces immediately before '(' or in '(...)' [for cases like
-- Input can also have multiple links in a single name like:
-- "British thermal unit (ISO)" and "Calorie (International Steam Table)"].
-- [[United States customary units|U.S.]] [[US gallon|gallon]]
local pos
-- [[mile]]s per [[United States customary units|U.S.]] [[quart]]
if name:sub(1, 1) == '(' then
-- [[long ton]]s per [[short ton]]
pos = name:find(')', 1, true)
-- Assume that links cannot be nested (never like "[[abc[[def]]ghi]]").
if pos then
-- This uses a simple and efficient procedure that works for most cases.
return name:sub(1, pos+1) .. name:sub(pos+2):gsub(' ', '-')
-- Some units (if used) would require more, and can later think about
end
-- adding a method to handle exceptions.
elseif name:sub(-1, -1) == ')' then
-- The procedure is to replace each space with a hyphen, but
pos = name:find('(', 1, true)
-- not a space after ')' [for "(pre-1954&nbsp;US) nautical mile"], and
if pos then
-- not spaces immediately before '(' or in '(...)' [for cases like
return name:sub(1, pos-2):gsub(' ', '-') .. name:sub(pos-1)
-- "British thermal unit (ISO)" and "Calorie (International Steam Table)"].
end
if name:find(' ', 1, true) then
end
if parts then
return name:gsub(' ', '-')
local pos
if name:sub(1, 1) == '(' then
pos = name:find(')', 1, true)
if pos then
return name:sub(1, pos+1) .. name:sub(pos+2):gsub(' ', '-')
end
elseif name:sub(-1, -1) == ')' then
pos = name:find('(', 1, true)
if pos then
return name:sub(1, pos-2):gsub(' ', '-') .. name:sub(pos-1)
end
end
return name:gsub(' ', '-')
end
parts = collection()
for before, item, after in name:gmatch('([^[]*)(%[%[[^[]*%]%])([^[]*)') do
if item:find(' ', 1, true) then
local prefix
local plen = item:find('|', 1, true)
if plen then
prefix = item:sub(1, plen)
item = item:sub(plen + 1, -3)
else
prefix = item:sub(1, -3) .. '|'
item = item:sub(3, -3)
end
item = prefix .. hyphenated(item, parts) .. ']]'
end
parts:add(before:gsub(' ', '-') .. item .. after:gsub(' ', '-'))
end
if parts.n == 0 then
-- No link like "[[...]]" was found in the original name.
parts:add(hyphenated(name, parts))
end
return table.concat(parts)
end
return name
end
 
local function hyphenated_maybe(parms, want_name, sep, id, inout)
-- Return s, f where
-- s = id, possibly modified
-- f = true if hyphenated
-- Possible modifications: hyphenate; prepend '-'; append mid text.
if id == nil or id == '' then
return ''
end
local mid = (inout == (parms.opt_flip and 'out' or 'in')) and parms.mid or ''
local mid
if want_name then
if parms.opt_adjectival then
return '-' .. hyphenated(id) .. mid, true
if inout == (parms.opt_flip and 'out' or 'in') then
end
mid = parms.mid
if parms.opt_add_s and id:sub(-1) ~= 's' then
end
id = id .. 's' -- for nowiki
if want_name then
end
return '-' .. hyphenated(id) .. (mid or ''), true
end
return sep .. id .. mid
end
return sep .. id .. (mid or '')
end
 
local function change_sign(text)
-- Change sign of text for correct appearance because it is negated.
if text:sub(1, 1) == '-' then
return text:sub(2)
end
return '-' .. text
end
 
local function use_minus(text)
-- Return text with Unicode minus instead of '-', if present.
if text:sub(1, 1) == '-' then
return MINUS .. text:sub(2)
end
return text
end
 
local function digit_grouper(method, gaps)
-- Return a table to hold groups of digits which can be joined with
-- suitable separators (such as commas).
-- Each group is separately translated to the local language because the
-- gap separators may include '.' charactersdigits which should not be translated.
-- Parameter method is a number or nil:
-- 3 for 3-digit grouping, or
-- 2 for 3-then-2 grouping.
-- Parameter gaps is true to use <span> gaps (numsep ignored).
return {
n = 0,
add = function (self, digits)
self.n = self.n + 1
self[self.n] = from_en(digits)
end,
join = function (self, rhs)
-- Concatenate in reverse order.
if gaps then
local result = ''
for i = 1, self.n - 1 do
result = '<span style="margin-left: 0.25em">' .. self[i] .. '</span>' .. result
end
end
return '<span style="white-space: nowrap">' .. self[self.n] .. result .. from_en(rhs) .. '</span>'
else
local result = self[1]
for i = 2, self.n do
result = self[i] .. numsep .. result
end
end
return result .. from_en(rhs)
end
end
end,
step = 3,
next_position = function (self, previous)
-- Return position of digit just before next group.
-- Digits are grouped from right-to-left (least significant first).
local result = previous - self.step
if method == 2 then
self.step = 2
self.step = 2 -- may need more (3, 2, 2, 3, 2, 2, ...) in some languages
end
end
return (result < 0) and 0 or result
end,
}
}
end
 
local function with_separator(parms, text)
-- Input text is a number in en digits and withoptional '.' decimal mark.
-- Return an equivalent of text, formatted for display:
-- with a custom decimal mark instead of '.', if wanted
-- with thousand separators inserted, if wanted
-- digits in local language
-- The given text is like '123' or '12345.6789' or '1.23e45'
-- (e notation can only occur when processing an input value).
-- The text has no sign (caller inserts that later, if necessary).
-- Separator is inserted only in the integer part of the significand
-- (not after the decimal mark, and not after 'e' or 'E').
if parms.opt_nocomma or numsep == '' then
return from_en(text)
end
local last = text:match('()[.eE]') -- () returns position
if last == nil then
last = #text
else
last = last - 1 -- index of last character before dot/e/E
end
if last < 4 or (last == 4 and parms.opt_comma5) then
return from_en(text)
end
local groups = digit_grouper(group_method, parms.opt_gaps)
local i = last
while i > 0 do
local position = groups:next_position(i)
groups:add(text:sub(position+1, i))
i = position
end
return groups:join(text:sub(last+1))
end
 
৭৬৩ ⟶ ৯৫৩ নং লাইন:
 
local function with_exponent(show, exponent)
-- Return wikitext to display the implied value in scientific notation.
-- Input uses en digits; output uses digits in local language.
if #show > 1 then
show = show:sub(1, 1) .. '.' .. show:sub(2)
end
return format(fmtpower, from_en(show), from_en('10'), use_minus(from_en(tostring(exponent))))
end
 
local function make_sigfig(value, sigfig)
-- Return show, exponent that are equivalent to the result of
-- converting the number 'value' (where value >= 0) to a string,
-- rounded to 'sigfig' significant figures.
-- The returned items are:
-- show: a string of digits; no sign and no dot;
-- there is an implied dot before show.
-- exponent: a number (an integer) to shift the implied dot.
-- Resulting value = tonumber('.' .. show) * 10^exponent.
-- Examples:
-- make_sigfig(23.456, 3) returns '235', 2 (.235 * 10^2).
-- make_sigfig(0.0023456, 3) returns '235', -2 (.235 * 10^-2).
-- make_sigfig(0, 3) returns '000', 1 (.000 * 10^1).
if sigfig <= 0 then
sigfig = 1
elseif sigfig > maxsigfig then
sigfig = maxsigfig
end
if value == 0 then
return string.rep('0', sigfig), 1
end
local exp, fracfracpart = math.modf(log10(value))
if fracfracpart >= 0 then
frac fracpart = fracfracpart - 1
exp = exp + 1
end
local digits = format('%.0f', 10^(fracfracpart + sigfig))
if #digits > sigfig then
-- Overflow (for sigfig=3: like 0.9999 rounding to "1000"; need "100").
digits = digits:sub(1, sigfig)
exp = exp + 1
end
assert(#digits == sigfig, 'Bug: rounded number has wrong length')
return digits, exp
end
 
local function format_number(parms, show, exponent, isnegative)
-- Parameter show is a number in en digits and with '.' decimal mark.
-- Return t where t is a table with fields:
-- show = wikitext formatted to display implied value
-- (digits in local language)
-- is_scientific = true if show uses scientific notation
-- clean = unformatted show (possibly adjusted and with inserted '.')
-- (en digits)
-- sign = '' or MINUS
-- exponent = exponent (possibly adjusted)
-- The clean and exponent fields can be used to calculate the
-- rounded absolute value, if needed.
--
-- The value implied by the arguments is found from:
-- exponent is nil; and
-- show is a string of digits (no sign), with an optional dot;
-- show = '123.4' is value 123.4, '1234' is value 1234.0;
-- or:
-- exponent is an integer indicating where dot should be;
-- show is a string of digits (no sign and no dot);
-- there is an implied dot before show;
-- show does not start with '0';
-- show = '1234', exponent = 3 is value 0.1234*10^3 = 123.4.
--
-- The formatted result:
-- * Is for an output value and is spelled if wanted and possible.
-- * Includes a Unicode minus if isnegative.
-- * Uses a custom decimal mark, if wanted.
-- * Has digits grouped where necessary, if wanted.
-- * Uses scientific notation for very small or large values
-- (which forces output to not be spelled).
-- * Has no more than maxsigfig significant digits
-- (same as old template and {{#expr}}).
local sign = isnegative and MINUS or ''
local maxlen = maxsigfig
if exponent == nil then
local integer, dot, fraction = show:match('^(%d*)(%.?)(.*)')
if #integer >= 10 then
show = integer .. fraction
exponent = #integer
elseif integer == '0' or integer == '' then
local zeros, figs = fraction:match('^(0*)([^0]?.*)')
if #figs == 0 then
if #zeros > maxlen then
show = '0.' .. zeros:sub(1, maxlen)
end
elseif #zeros >= 4 then
show = figs
exponent = -#zeros
elseif #figs > maxlen then
show = '0.' .. zeros .. figs:sub(1, maxlen)
end
else
maxlen = maxlen + #dot
if #show > maxlen then
show = show:sub(1, maxlen)
end
end
end
if exponent then
if #show > maxlen then
show = show:sub(1, maxlen)
end
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 {
clean = '.' .. show,
exponent = exponent,
sign = sign,
show = sign .. with_exponent(show, exponent-1),
is_scientific = true,
}
end
if exponent >= #show then
show = show .. string.rep('0', exponent - #show) -- result has no dot
elseif exponent <= 0 then
show = '0.' .. string.rep('0', -exponent) .. show
else
show = show:sub(1, exponent) .. '.' .. show:sub(exponent+1)
end
end
if isnegative and show:match('^0.?0*$') then
sign = '' -- don't show minus if result is negative but rounds to zero
end
local formatted_show = sign .. with_separator(parms, show)
if parms.opt_spell_out then
formatted_show = spell_number(parms, sign .. show) or formatted_show
end
return {
clean = show,
sign = sign,
show = formatted_show,
}
end
 
-- Fraction output format.
-- 2013-07-20 Trying new styles proposed at [[Template talk:Convert]].
local fracfmt = {
{ -- Like {{frac}} (fraction slash).
-- 1/2 : sign, numerator, denominator
-- 1+2/3 : signed_wholenumber, numerator, denominator
'<span class="frac nowrap">%s<sup>%s</sup>&frasl;<sub>%s</sub></span>',
'<span class="frac nowrap">%s<span class="visualhide">&nbsp;</span><sup> %s</sup>&frasl;<sub>%s</sub></span>',
},
{ -- Like {{sfrac}} (fraction horizontal bar).
-- 1//2 : sign, numerator, denominator (sign should probably be before the fraction, but then it can wrap, and html is already too long)
-- 1+2//3 : signed_wholenumber, numerator, denominator
'<span class="sfrac nowrap" style="display:inline-block; vertical-align:-0.5em; font-size:85%%; text-align:center;"><span style="display:block; line-height:1em; padding:0 0.1em;">%s%s</span><span styleclass="display:none;visualhide">/</span><span style="display:block; line-height:1em; padding:0 0.1em; border-top:1px solid;">%s</span></span>',
'<span class="sfrac nowrap">%s<span styleclass="display:none;visualhide">&nbsp;</span><span style="display:inline-block; vertical-align:-0.5em; font-size:85%%; text-align:center;"><span style="display:block; line-height:1em; padding:0 0.1em;">%s</span><span styleclass="display:none;visualhide">/</span><span style="display:block; line-height:1em; padding:0 0.1em; border-top:1px solid;">%s</span></span></span>',
},
{ -- Like old {{convert}} template.
-- 1///2 : sign, numerator, denominator
-- 1+2///3: signed_wholenumber, sign, numerator, denominator
'<span style="white-space:nowrap">%s<sup>%s</sup>&frasl;<sub>%s</sub></span>',
'<span class="frac nowrap">%s<s style="display:none">%s</s><sup>%s</sup>&frasl;<sub>%s</sub></span>',
},
}
 
local function format_fraction(parms, inout, negative, wholestr, numstr, denstr, do_spell, style)
-- Return wikitext for a fraction, possibly spelled.
-- Inputs use en digits and have no sign; output uses digits in local language.
local wikitext
if not style then
style = parms.opt_fraction_horizontal and 2 or 1
end
if wholestr == '' then
wholestr = nil
end
if wholestr then
local decorated = with_separator(parms, wholestr)
if negative then
decorated = MINUS .. decorated
end
local fmt = fracfmt[style][2]
wikitext = format(fmt, decorated, from_en(numstr), from_en(denstr))
else
local sign = negative and MINUS or ''
wikitext = format(fracfmt[style][1], sign, from_en(numstr), from_en(denstr))
end
if do_spell then
if negative then
if wholestr then
wholestr = '-' .. wholestr
else
numstr = '-' .. numstr
end
end
wikitext = spell_number(parms, inout, wholestr, numstr, denstr) or wikitext
end
return wikitext
end
 
local function format_number(parms, show, exponent, isnegative)
-- Parameter show is a string or a table containing strings.
-- Each string is a formatted number in en digits and optional '.' decimal mark.
-- A table represents a fraction: integer, numerator, denominator;
-- if a table is given, exponent must be nil.
-- Return t where t is a table with fields:
-- show = wikitext formatted to display implied value
-- (digits in local language)
-- is_scientific = true if show uses scientific notation
-- clean = unformatted show (possibly adjusted and with inserted '.')
-- (en digits)
-- sign = '' or MINUS
-- exponent = exponent (possibly adjusted)
-- The clean and exponent fields can be used to calculate the
-- rounded absolute value, if needed.
--
-- The value implied by the arguments is found from:
-- exponent is nil; and
-- show is a string of digits (no sign), with an optional dot;
-- show = '123.4' is value 123.4, '1234' is value 1234.0;
-- or:
-- exponent is an integer indicating where dot should be;
-- show is a string of digits (no sign and no dot);
-- there is an implied dot before show;
-- show does not start with '0';
-- show = '1234', exponent = 3 is value 0.1234*10^3 = 123.4.
--
-- The formatted result:
-- * Is for an output value and is spelled if wanted and possible.
-- * Includes a Unicode minus if isnegative and not spelled.
-- * Uses a custom decimal mark, if wanted.
-- * Has digits grouped where necessary, if wanted.
-- * Uses scientific notation for very small or large values
-- (which forces output to not be spelled).
-- * Has no more than maxsigfig significant digits
-- (same as old template and {{#expr}}).
local sign = isnegative and MINUS or ''
local maxlen = maxsigfig
local tfrac
if type(show) == 'table' then
tfrac = show
show = tfrac.wholestr
assert(exponent == nil, 'Bug: exponent given with fraction')
end
if not tfrac and not exponent then
local integer, dot, decimals = show:match('^(%d*)(%.?)(.*)')
if #integer >= 10 then
show = integer .. decimals
exponent = #integer
elseif integer == '0' or integer == '' then
local zeros, figs = decimals:match('^(0*)([^0]?.*)')
if #figs == 0 then
if #zeros > maxlen then
show = '0.' .. zeros:sub(1, maxlen)
end
elseif #zeros >= 4 then
show = figs
exponent = -#zeros
elseif #figs > maxlen then
show = '0.' .. zeros .. figs:sub(1, maxlen)
end
else
maxlen = maxlen + #dot
if #show > maxlen then
show = show:sub(1, maxlen)
end
end
end
if exponent then
if #show > maxlen then
show = show:sub(1, maxlen)
end
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 {
clean = '.' .. show,
exponent = exponent,
sign = sign,
show = sign .. with_exponent(show, exponent-1),
is_scientific = true,
}
end
if exponent >= #show then
show = show .. string.rep('0', exponent - #show) -- result has no dot
elseif exponent <= 0 then
show = '0.' .. string.rep('0', -exponent) .. show
else
show = show:sub(1, exponent) .. '.' .. show:sub(exponent+1)
end
end
local formatted_show
if tfrac then
show = tostring(tfrac.value) -- to set clean in returned table
formatted_show = format_fraction(parms, 'out', isnegative, tfrac.wholestr, tfrac.numstr, tfrac.denstr, parms.opt_spell_out)
else
if isnegative and show:match('^0.?0*$') then
sign = '' -- don't show minus if result is negative but rounds to zero
end
formatted_show = sign .. with_separator(parms, show)
if parms.opt_spell_out then
formatted_show = spell_number(parms, 'out', sign .. show) or formatted_show
end
end
return {
clean = show,
sign = sign,
show = formatted_show,
is_scientific = false, -- to avoid calling __index
}
end
 
local function extract_fraction(parms, text, negative)
-- If text represents a fraction, return
-- value, altvalue, show, spelled, wheredenominator
-- where
-- value is a number (value of the fraction in argument text)
-- showvalue is a stringnumber (formattedvalue textof forthe displayfraction ofin anargument input value,text)
-- altvalue is an alternate interpretation of any fraction for the hands
-- and is spelled if wanted and possible)
-- -- unit spelledwhere is"14.1+3/4" truemeans if14 showhands was1.75 spelledinches!
-- show is a string (formatted text for display of an input value,
-- Otherwise, return nil.
-- -- Input uses en digits and '.'is decimalspelled markif (inputwanted has beenand translatedpossible).
-- spelled is true if show was spelled
-- Output uses digits in local language and custom decimal mark, if any.
-- denominator is value of the denominator in the fraction
--
-- Otherwise, return nil.
-- In the following, '(3/8)' represents the wikitext required to
-- Input uses en digits and '.' decimal mark (input has been translated).
-- display a fraction with numerator 3 and denominator 8.
-- Output uses digits in local language and custom decimal mark, if any.
-- In the wikitext, Unicode minus is used for a negative value.
--
-- text value, show value, show
-- In the following, '(3/8)' represents the wikitext required to
-- if not negative if negative
-- display a fraction with numerator 3 and denominator 8.
-- 3 / 8 0.375, '(3/8)' -0.375, '−(3/8)'
-- In the wikitext, Unicode minus is used for a negative value.
-- 2 + 3 / 8 2.375, '2(3/8)' -1.625, '−2(−3/8)'
-- text -- 2 - 3 / 8 value, show 1.625, '2(−3/8)' -2.375 value, '−2(3/8)'show
-- -- 1 + 20/8 3.5 ,if '1/(20/8)'not negative 1.5 ,if '−1/(−20/8)'negative
-- 3 --/ 8 1 - 20/8 -1.50.375, '1(−203/8)' -30.5 375, '−1(203/8)'
-- 2 + 3 / 8 2.375, '2(3/8)' -1.625, '−2(−3/8)'
-- Wherever an integer appears above, numbers like 1.25 or 12.5e-3
-- 2 - 3 / 8 1.625, '2(−3/8)' -2.375, '−2(3/8)'
-- (which may be negative) are also accepted (like old template).
-- 1 + 20/8 3.5 , '1/(20/8)' 1.5 , '−1/(−20/8)'
-- Template interprets '1.23e+2+12/24' as '123(12/24)' = 123.5!
-- 1 - 20/8 -1.5., '1(−20/8)' -3.5 , '−1(20/8)'
local numstr, whole, value
-- Wherever an integer appears above, numbers like 1.25 or 12.5e-3
local lhs, slash, denstr = text:match('^%s*([^/]-)%s*(/+)%s*(.-)%s*$')
-- (which may be negative) are also accepted (like old template).
local denominator = tonumber(denstr)
-- Old template interprets '1.23e+2+12/24' as '123(12/24)' = 123.5!
if denominator == nil then return nil end
local numstr, whole, value, altvalue
local wholestr, negfrac, rhs = lhs:match('^%s*(.-[^eE])%s*([+-])%s*(.-)%s*$')
local lhs, slash, denstr = text:match('^%s*([^/]-)%s*(/+)%s*(.-)%s*$')
if wholestr == nil or wholestr == '' then
local denominator = tonumber(denstr)
wholestr = nil
if denominator == nil then return nil end
whole = 0
local wholestr, negfrac, rhs = lhs:match('^%s*(.-[^eE])%s*([+-])%s*(.-)%s*$')
numstr = lhs
if wholestr == nil or wholestr == '' then
else
wholestr = nil
whole = tonumber(wholestr)
whole = 0
if whole == nil then return nil end
numstr = rhslhs
else
end
whole = tonumber(wholestr)
negfrac = (negfrac == '-')
if whole == nil then return nil end
local numerator = tonumber(numstr)
numstr = rhs
if numerator == nil then return nil end
end
-- Spelling of silly inputs like "-2+3/8" or "2+3/+8" (mixed or excess signs) is not supported.
negfrac = (negfrac == '-')
local do_spell
local numerator = tonumber(numstr)
if negative == negfrac or wholestr == nil then
if numerator == nil then return nil end
value = whole + numerator / denominator
-- Spelling of silly inputs like "-2+3/8" or "2+3/+8" (mixed or excess signs) is not supported.
do_spell = parms.opt_spell_in
if local do_spell then
if negative == negfrac or wholestr == nil then
if not (numstr:match('^%d') and denstr:match('^%d')) then -- if either has a sign
value = whole + numerator / denominator
do_spell = false
altvalue = whole + numerator / (denominator * 10)
end
do_spell = parms.opt_spell_in
end
if do_spell then
else
if not (numstr:match('^%d') and denstr:match('^%d')) then -- if either has a sign
value = whole - numerator / denominator
do_spell = false
numstr = change_sign(numstr)
end
do_spell = false
end
else
if not valid_number(value) then
value = whole - numerator / denominator
return nil -- overflow or similar
altvalue = whole - numerator / (denominator * 10)
end
numstr = use_minuschange_sign(numstr)
do_spell = false
denstr = use_minus(denstr)
end
local style = #slash -- kludge: 1, 2, or 3 slashes can be used to select style
if not valid_number(value) then
if style > 3 then style = 3 end
return nil -- overflow or similar
local wikitext
end
if wholestr then
numstr = use_minus(numstr)
if negative then
denstr = use_minus(denstr)
wholestr = change_sign(wholestr)
local style = #slash -- kludge: 1 or 2 slashes can be used to select style
end
if style > 2 then style = 2 end
local fmt = fracfmt[style][2]
local wikitext = format_fraction(parms, 'in', negative, wholestr, numstr, denstr, do_spell, style)
if style < 3 then
return value, altvalue, wikitext, do_spell, denominator
wikitext = format(fmt, use_minus(from_en(wholestr)), from_en(numstr), from_en(denstr))
else
local sign = negative and MINUS or '+'
wikitext = format(fmt, use_minus(from_en(wholestr)), sign, from_en(numstr), from_en(denstr))
end
else
local sign = negative and MINUS or ''
wikitext = format(fracfmt[style][1], sign, from_en(numstr), from_en(denstr))
end
if do_spell then
local numsign = (wholestr or not negative) and '' or '-'
wikitext = spell_number(parms, wholestr, numsign .. numstr, denstr) or wikitext
end
return value, wikitext, do_spell
end
 
local function extract_number(parms, text, another, no_fraction)
-- Return true, info if can extract a number from text,
-- where info is a table with the result,
-- or return false, t where t is an error message table.
-- Input can use en digits or digits in local language.
-- Parameter another = true if the expected value is not the first.
-- Before processing, the input text is cleaned:
-- * Any thousand separators (valid or not) are removed.
-- * Any sign (and optional following whitespace) is replaced with
-- '-' (if negative) or '' (otherwise).
-- That replaces Unicode minus with '-'.
-- If successful, the returned info table contains named fields:
-- value = a valid number
-- altvalue = a valid number, usually same as value but different
-- singular = true if value is 1 (to use singular form of units)
-- = false if valuefraction is -1used (likefor oldhands templateunit)
-- cleansingular = true if =value cleanedis text1 with(to anyuse separatorssingular andform signof removedunits)
-- -- = false if value is -1 (en digits and '.'like decimalold marktemplate)
-- clean = cleaned text with any separators and sign removed
-- show = text formatted for output
-- (en digits in local language and custom'.' decimal mark)
-- show = text formatted for output
-- The resulting show:
-- -- * Is for an input value and is spelled if(digits wantedin local language and possible.custom decimal mark)
-- The resulting show:
-- * Has a rounded value, if wanted.
-- * HasIs digitsfor groupedan whereinput necessary,value and is spelled if wanted and possible.
-- * Has a rounded value, if wanted.
-- * If negative, a Unicode minus is used; otherwise the sign is
-- * Has digits grouped where necessary, if wanted.
-- '+' (if the input text used '+'), or is '' (if no sign in input).
-- * If negative, a Unicode minus is used; otherwise the sign is
text = strip(text or '')
-- '+' (if the input text used '+'), or is '' (if no sign in input).
local clean = to_en(text)
text = strip(text or '')
if clean == '' then
local clean = to_en(text)
return false, { another and 'cvt_no_num2' or 'cvt_no_num' }
if clean == '' then
end
return false, { another and 'cvt_no_num2' or 'cvt_no_num' }
local isnegative, propersign = false, '' -- most common case
end
local singular, show
local isnegative, propersign = false, '' -- most common case
local value = tonumber(clean)
local singular, show, denominator
if value then
local signvalue = tonumber(clean:sub(1, 1)
local altvalue
if sign == '+' or sign == '-' then
if value then
propersign = (sign == '+') and '+' or MINUS
local cleansign = clean:sub(21, 1)
if sign == '+' or sign == '-' endthen
propersign = (sign == '+') and '+' or MINUS
if value < 0 then
clean = clean:sub(2)
isnegative = true
end
value = -value
if value < 0 then
end
isnegative = true
else
value = -value
local valstr
end
for _, prefix in ipairs({ '-', MINUS, '&minus;' }) do
else
-- Including '-' means inputs like '- 2' (with space) are accepted as -2.
local valstr
-- It also sets isnegative in case input is a fraction like '-2-3/4'.
for _, prefix in ipairs({ '-', MINUS, '&minus;' }) do
local plen = #prefix
-- Including '-' means inputs like '- 2' (with space) are accepted as -2.
if clean:sub(1, plen) == prefix then
-- It also sets isnegative in case input is a fraction like '-2-3/4'.
valstr = clean:sub(plen + 1)
local plen = #prefix
break
if clean:sub(1, plen) == prefix then
end
valstr = clean:sub(plen + 1)
end
break
if valstr then
end
isnegative = true
end
propersign = MINUS
if valstr then
clean = valstr
isnegative = true
value = tonumber(clean)
propersign = MINUS
end
clean = valstr
if value == nil then
value = tonumber(clean)
local spelled
end
if not no_fraction then
if value == nil then
value, show, spelled = extract_fraction(parms, clean, isnegative)
local spelled
end
if value ==not nilno_fraction then
value, altvalue, show, spelled, denominator = extract_fraction(parms, clean, isnegative)
return false, { 'cvt_bad_num', text }
end
end
if spelled and value <== 1nil then
return false, { 'cvt_bad_num', text }
singular = true -- for example, "one half mile" (singular unit)
end
else
if value <= 1 then
singular = false -- any numeric fraction (even with value 1) is regarded as plural
singular = true -- for example, "½ mile" or "one half mile" (singular unit)
end
end
end
end
if not valid_number(value) then -- for example, "1e310" overflows
if not valid_number(value) then -- for example, "1e310" may overflow
return false, { 'cvt_invalid_num' }
return false, { 'cvt_invalid_num' }
end
end
if show == nil then
if show == nil then
singular = (value == 1 and not isnegative)
local precision = parms.input_precision
if precision and 0 <= precision and precision <= 8 then
local fmt = '%.' .. format('%d', precision) .. 'f'
value = value + 2e-14 -- fudge for some common cases of bad rounding
show = fmt:format(value + 2e-14) -- fudge for some common cases of bad rounding
local fmt = '%.' .. format('%d', precision) .. 'f'
else
show = fmt:format(value)
show = clean
else
end
show = clean
show = propersign .. with_separator(parms, show)
end
if parms.opt_spell_in then
show = propersign .. with_separator(parms, show)
show = spell_number(parms, 'in', propersign .. clean) or show
if parms.opt_spell_in then
end
show = spell_number(parms, propersign .. clean) or show
end
local altvalue = altvalue or value
end
if isnegative and (value ~= 0) then
value = -value
altvalue = -altvalue
end
end
return true, {
return true, {
value = value,
value = value,
singular = singular,
altvalue = altvalue,
clean = clean,
singular = singular,
show = show,
clean = clean,
}
show = show,
denominator = denominator,
}
end
 
local function get_number(text)
-- Return v, f where:
-- v = nil (text is not a number)
-- or
-- v = value of text (text is a number)
-- f = true if value is an integer
-- Input can use en digits or digits in local language,
-- but no separators, no Unicode minus, and no fraction.
if text then
local number = tonumber(to_en(text))
if number then
local integer, fractionfracpart = math.modf(number)
return number, (fractionfracpart == 0)
end
end
end
 
local function gcd(a, b)
-- Return the greatest common denominator for the given values,
-- which are known to be positive integers.
if a > b then
a, b = b, a
end
if a <= 0 then
return b
end
local r = b % a
if r <= 0 then
return a
end
if r == 1 then
return 1
end
return gcd(r, a)
end
 
local function fraction_table(value, denominator)
-- Return value as a string or a table:
-- * If result is a string, there is no fraction, and the result
-- is value formatted as a string of en digits.
-- * If result is a table, it represents a fraction with named fields:
-- wholestr, numstr, denstr (strings of en digits for integer, numerator, denominator).
-- The result is rounded to the nearest multiple of (1/denominator).
-- If the multiple is zero, no fraction is included.
-- No fraction is included if value is very large as the fraction would
-- be unhelpful, particularly if scientific notation is required.
-- Input value is a non-negative number.
-- Input denominator is a positive integer for the desired fraction.
if value <= 0 then
return '0'
end
if denominator <= 0 or value > 1e8 then
return format('%.2f', value)
end
local integer, decimals = math.modf(value)
local numerator = floor((decimals * denominator) +
0.5 + 2e-14) -- add fudge for some common cases of bad rounding
if numerator >= denominator then
integer = integer + 1
numerator = 0
end
local wholestr = tostring(integer)
if numerator > 0 then
local div = gcd(numerator, denominator)
if div > 1 then
numerator = numerator / div
denominator = denominator / div
end
return {
wholestr = (integer > 0) and wholestr or '',
numstr = tostring(numerator),
denstr = tostring(denominator),
value = value,
}
end
return wholestr
end
 
local function preunits(count, preunit1, preunit2)
-- If count is 1:
-- ignore preunit2
-- return p1
-- else:
-- preunit1 is used for preunit2 if the latter is empty
-- return p1, p2
-- where:
-- p1 is text to insert before the input unit
-- p2 is text to insert before the output unit
-- p1 or p2 may be nil to mean "no preunit"
-- Using '+ ' gives output like "5+ feet" (no preceding space).
local function withspace(text, i)
-- Insert space at beginning if i == 1, or at end if i == -1.
-- However, no space is inserted if there is a space or '&nbsp;'
-- or '-' at that position ('-' is for adjectival text).
local current = text:sub(i, i)
if current == ' ' or current == '-' then
return text
end
if i == 1 then
current = text:sub(1, 6)
else
current = text:sub(-6, -1)
end
if current == '&nbsp;' then
return text
end
if i == 1 then
return ' ' .. text
end
return text .. ' '
end
preunit1 = preunit1 or ''
local trim1 = strip(preunit1)
if count == 1 then
if trim1 == '' then
return nil
end
return withspace(withspace(preunit1, 1), -1)
end
preunit2 = preunit2 or ''
local trim2 = strip(preunit2)
if trim1 == '' and trim2 == '' then
return nil, nil
end
if trim1 ~= '+' then
preunit1 = withspace(preunit1, 1)
end
if trim2 == '&#32;' then -- trick to make preunit2 empty
preunit2 = nil
elseif trim2 == '' then
preunit2 = preunit1
elseif trim2 ~= '+' then
preunit2 = withspace(preunit2, 1)
end
return preunit1, preunit2
end
 
local function range_text(range, want_name, parms, before, after)
-- Return before .. rtext .. after
-- where rtext is the text that separates two values in a range.
local rtext, adj_text, exception
if type(range) == 'table' then
-- Table must specify range text for abbr=off and for abbr=on,
-- and may specify range text for 'adj=on',
-- and may specify exception = true.
rtext = range[want_name and 'off' or 'on']
adj_text = range['adj']
exception = range['exception']
else
rtext = range
end
if parms.opt_adjectival then
if want_name or (exception and parms.abbr_org == 'on') then
rtext = adj_text or rtext:gsub(' ', '-'):gsub('&nbsp;', '-')
end
end
if rtext == '–' and after:sub(1, #MINUS) == MINUS then
rtext = '&nbsp;– '
end
return before .. rtext .. after
end
 
local function get_composite(parms, iparm, total, in_unit_table)
-- Look for a composite input unit. For example, "{{convert|1|yd|2|ft|3|in}}"
-- would result in a call to this function with
-- iparm = 3 (parms[iparm] = "2", just after the first unit)
-- total = 1 (number of yards)
-- in_unit_table = (unit table for "yd")
-- Return true, iparm, unit where
-- iparm = index just after the composite units (7 in above example)
-- unit = composite unit table holding all input units,
-- or return true if no composite unit is present in parms,
-- or return false, t where t is an error message table.
local default, subinfo
local composite_units, count = { in_unit_table }, 1
local fixups = {}
local subunit = in_unit_table
while subunit.subdivs do -- subdivs is nil or a table of allowed subdivisions
local subcode = strip(parms[iparm+1])
local subdiv = subunit.subdivs[subcode]
if not subdiv then
break
end
local success
success, subunit = lookup(subcode, parms.opt_sp_us, 'no_combination')
if not success then return false, subunit end -- should never occur
success, subinfo = extract_number(parms, parms[iparm])
if not success then return false, subinfo end
iparm = iparm + 2
subunit.inout = 'in'
subunit.valinfo = { subinfo }
-- Recalculate total as a number of subdivisions.
-- subdiv[1] = number of subdivisions per previous unit (integer > 1).
total = total * subdiv[1] + subinfo.value
if not default then -- set by the first subdiv with a default defined
default = subdiv.default
end
count = count + 1
composite_units[count] = subunit
if subdiv.unit or subdiv.name then
fixups[count] = { unit = subdiv.unit, name = subdiv.name, valinfo = subunit.valinfo }
end
end
if count == 1 then
return true -- no error and no composite unit
end
for i, fixup in pairs(fixups) do
local unit = fixup.unit
local name = fixup.name
if not unit or (count > 2 and name) then
composite_units[i].fixed_name = name
else
local success, alternate = lookup(unit, parms.opt_sp_us, 'no_combination')
if not success then return false, alternate end -- should never occur
alternate.inout = 'in'
alternate.valinfo = fixup.valinfo
composite_units[i] = alternate
end
end
return true, iparm, {
utype = in_unit_table.utype,
scale = subunit.scale, -- scale of last (least significant) unit
valinfo = { { value = total, clean = subinfo.clean, denominator = subinfo.denominator } },
composite = composite_units,
default = default or in_unit_table.default
}
}
end
 
local function translate_parms(parms, named_keyskv_pairs)
-- Update fields in parms by translating parameterseach tokey:value thosein usedkv_pairs atto enwiki.terms
-- used by this module (may involve translating from local language to English).
-- Also, checks are performed which may display warnings, if enabled.
-- Also, checks are performed which may display warnings, if enabled.
-- Return true if successful or return false, t where t is an error message table.
-- Return true if successful or return false, t where t is an error message table.
for _, loc_name in ipairs(named_keys) do
if kv_pairs.adj and kv_pairs.sing then
local loc_value = parms[loc_name]
-- For enwiki (before translation), warn if attempt to use adj and sing
local en_name = en_option_name[loc_name]
-- as the latter is a deprecated alias for the former.
if en_name then
if kv_pairs.adj ~= kv_pairs.sing and kv_pairs.sing ~= '' then
local en_value
add_warning(parms, 1, 'cvt_unknown_option', 'sing=' .. kv_pairs.sing)
if en_name == 'sigfig' then
end
if loc_value == '' then
kv_pairs.sing = nil
add_warning(parms, 'cvt_empty_option', loc_name)
end
else
for loc_name, loc_value in pairs(kv_pairs) do
local number, is_integer = get_number(loc_value)
local en_name = text_code.en_option_name[loc_name]
if not number or not is_integer or number <= 0 then
if en_name then
return false, { 'cvt_bad_sigfig', loc_value }
local en_value
end
if en_name == 'frac' or en_name == 'sigfig' then
en_value = number
if loc_value == '' then
end
add_warning(parms, 2, 'cvt_empty_option', loc_name)
else
else
en_value = en_option_value[en_name][loc_value]
local minimum
end
local number, is_integer = get_number(loc_value)
if en_value == nil then
if loc_valueen_name == 'frac' then
minimum = 2
add_warning(parms, 'cvt_empty_option', loc_name)
if number and number < 0 then
else
parms.opt_fraction_horizontal = true
-- Using, for example, aliases like |sing=off|adj=on can give
number = -number
-- loc_value == nil when adj is processed after sing. In that case,
end
-- the following gives a slightly misleading but reasonable warning.
else
local text = loc_value and (loc_name .. '=' .. loc_value) or loc_name
minimum = 1
add_warning(parms, 'cvt_unknown_option', text)
end
end
if number and is_integer and number >= minimum then
elseif en_value == '' then
en_value = number
en_value = nil -- an ignored option like adj=off
else
elseif type(en_value) == 'string' and en_value:sub(1, 4) == 'opt_' then
add_warning(parms, 1, (en_name == 'frac' and 'cvt_bad_frac' or 'cvt_bad_sigfig'), loc_value)
for _, v in ipairs(split(en_value, ',')) do
end
parms[v] = true
end
end
else
en_value = nil
en_value = text_code.en_option_value[en_name][loc_value]
end
if en_value == nil then
parms[en_name] = en_value
if loc_value == '' then
else
add_warning(parms, 2, 'cvt_unknown_optioncvt_empty_option', loc_name .. '=' .. loc_value)
else
end
-- loc_value can no longer be nil here (at one time, that could occur
end
-- with aliases like |sing=off|adj=on), but am retaining safety check.
if parms.adj then
local text = loc_value and (loc_name .. '=' .. loc_value) or loc_name
if parms.adj:sub(1, 2) == 'ri' then
add_warning(parms, 1, 'cvt_unknown_option', text)
-- It is known that adj is 'ri1' or 'ri2' or 'ri3', so precision is valid.
end
-- Only en digits are accepted.
elseif en_value == '' then
parms.input_precision = tonumber(parms.adj:sub(-1))
en_value = nil -- an ignored option like adj=off
parms.adj = nil
elseif type(en_value) == 'string' and en_value:sub(1, 4) == 'opt_' then
end
for _, v in ipairs(split(en_value, ',')) do
end
parms[v] = true
if parms.abbr then
end
parms.abbr_org = parms.abbr -- original abbr that was set, before any flip
en_value = nil
else
end
parms.abbr = 'out' -- default is to abbreviate output only (use symbol, not name)
end
parms[en_name] = en_value
if parms.opt_flip then
else
local function swap_in_out(option)
add_warning(parms, 1, 'cvt_unknown_option', loc_name .. '=' .. loc_value)
local value = parms[option]
end
if value == 'in' then
end
parms[option] = 'out'
if parms.adj then
elseif value == 'out' then
if parms.adj:sub(1, 2) == 'ri' then
parms[option] = 'in'
-- It is known that adj is 'riN' where N is a single digit, so precision is valid.
end
-- Only a single en digit is accepted.
end
parms.input_precision = tonumber(parms.adj:sub(-1))
swap_in_out('abbr')
parms.adj = nil
swap_in_out('lk')
end
if parms.opt_spell_in then
end
-- For simplicity, and because it does not appear to be needed,
local cfg_abbr = config.abbr
-- user cannot set an option to spell the output.
if cfg_abbr then
parms.opt_spell_in = nil
-- Don't warn if invalid because every convert would show that warning.
parms.opt_spell_out = true
if cfg_abbr == 'on always' then
end
parms.abbr = 'on'
end
elseif cfg_abbr == 'off always' then
if parms.opt_table or parms.opt_tablecen then
parms.abbr = 'off'
if parms.abbr_org == nil and parms.lk == nil then
elseif parms.opt_valuesabbr == nil truethen
if cfg_abbr == 'on default' then
end
parms.abbr = 'on'
local align = format('align="%s"', parms.opt_table and 'right' or 'center')
elseif cfg_abbr == 'off default' then
parms.table_joins = { align .. '|', '\n|' .. align .. '|' }
parms.abbr = 'off'
end
end
if parms.opt_lang_en then
end
from_en_table = nil
end
if parms.abbr then
return true
parms.abbr_org = parms.abbr -- original abbr that was set, before any flip
elseif parms.opt_hand_hh then
parms.abbr_org = 'on'
parms.abbr = 'on'
else
parms.abbr = 'out' -- default is to abbreviate output only (use symbol, not name)
end
if parms.opt_flip then
local function swap_in_out(option)
local value = parms[option]
if value == 'in' then
parms[option] = 'out'
elseif value == 'out' then
parms[option] = 'in'
end
end
swap_in_out('abbr')
swap_in_out('lk')
if parms.opt_spell_in and not parms.opt_spell_out then
-- For simplicity, and because it does not appear to be needed,
-- user cannot set an option to spell the output only.
parms.opt_spell_in = nil
parms.opt_spell_out = true
end
end
if parms.opt_spell_upper then
parms.spell_upper = parms.opt_flip and 'out' or 'in'
end
if parms.opt_table or parms.opt_tablecen then
if parms.abbr_org == nil and parms.lk == nil then
parms.opt_values = true
end
local align = format('align="%s"', parms.opt_table and 'right' or 'center')
parms.table_joins = { align .. '|', '\n|' .. align .. '|' }
end
if parms.opt_lang_en then
from_en_table = nil
end
return true
end
 
local function get_values(parms)
-- If successful, update parms and return true, v, i where
-- v = table of input values
-- i = index to next entry in parms after those processed here
-- or return false, t where t is an error message table.
local valinfo = collection() -- numbered table of input values
local range = collection() -- numbered table of range items (having, for example, 2 range items requires 3 input values)
local had_nocomma -- true if removed "nocomma" kludge from second parameter (like "tonocomma")
local parm2 = strip(parms[2])
if parm2 and parm2:sub(-7, -1) == 'nocomma' then
parms[2] = strip(parm2:sub(1, -8))
parms.opt_nocomma = true
had_nocomma = true
end
local function extractor(i)
local i = 1
-- If the parameter is not a value, try unpacking it as a range ("1-23" for "1 to 23").
while true do
-- However, "-1-2/3" is a negative fraction (-1⅔), so it must be extracted first.
local success, info = extract_number(parms, parms[i], i > 1) -- need to set parms.opt_nocomma before calling this
-- Unpacked items are inserted into the parms table.
if not success then return false, info end
local valstr = strip(parms[i]) -- trim so any '-' as a negative sign will be at start
i = i + 1
local success, result = extract_number(parms, valstr, i > 1)
valinfo:add(info)
if not success and valstr and i < 20 then -- check i to limit abuse
local next = strip(parms[i])
for _, sep in ipairs(text_code.ranges.words) do
local range_item = range_types[next] or range_types[range_aliases[next]]
local start, stop = valstr:find(sep, 2, true) -- start at 2 to skip any negative sign for range '-'
if not range_item then
if start then
break
parms[i] = valstr:sub(stop + 1)
end
table.insert(parms, i, sep)
i = i + 1
table.insert(parms, i, valstr:sub(1, start - 1))
range:add(range_item)
return extractor(i) -- this allows combinations like "1 x 2 to 3 x 4"
parms.is_range_x = (type(range_item) == 'table') and range_item.is_range_x or nil
end
end
if range.n > 0 then
end
if range.n > 30 then -- limit abuse, although 4 is a more likely upper limit
return success, result
return false, { 'cvt_invalid_num' } -- misleading message but it will do
end
local i = 1
parms.range = range
local is_change
elseif had_nocomma then
while true do
return false, { 'cvt_unknown', parm2 }
local success, info = extractor(i) -- need to set parms.opt_nocomma before calling this
end
if not success then return truefalse, valinfo,info iend
i = i + 1
if is_change then
info.is_change = true -- value is after "±" and so is a change (significant for range like {{convert|5|±|5|°C}})
is_change = nil
end
valinfo:add(info)
local next = strip(parms[i])
local range_item = get_range(next)
if not range_item then
break
end
i = i + 1
range:add(range_item)
if type(range_item) == 'table' then
parms.is_range_x = range_item.is_range_x
is_change = range_item.is_range_change
end
end
if range.n > 0 then
if range.n > 30 then -- limit abuse, although 4 is a more likely upper limit
return false, { 'cvt_invalid_num' } -- misleading message but it will do
end
parms.range = range
elseif had_nocomma then
return false, { 'cvt_unknown', parm2 }
end
return true, valinfo, i
end
 
local function simple_get_values(parms)
-- If input is like "{{convert|valid_value|valid_unit|...}}",
-- return true, v, 3, in_unit, in_unit_table
-- (as for get_values(), but with a unit name and table for a valid unit;
-- 3 = index in parms of whatever follows valid_unit, if anything).
-- The valid_value is not negative and does not use a fraction, and
-- no options requiring further processing of the input are used.
-- Otherwise, return nothing and caller will reparse the input.
-- Testing shows this function is successful for 96% of converts in articles,
-- and that on average it speeds up converts by 8%.
if parms.input_precision or parms.opt_spell_in then return end
local clean = to_en(strip(parms[1] or ''))
if #clean > 10 or not clean:match('^[0-9.]+$') then return end
local value = tonumber(clean)
if not value then return end
local info = {
value = value,
altvalue = value,
singular = (value == 1),
clean = clean,
show = with_separator(parms, clean),
}
local in_unit = strip(parms[2])
local success, in_unit_table = lookup(in_unit, parms.opt_sp_us, 'no_combination')
if not success then return end
return true, { info }, 3, in_unit, in_unit_table
end
 
local function get_parms(pframe)
-- If successful, return true, parms, unit where
-- parms is a table of all arguments passed to the template
-- converted to named arguments, and
-- unit is the input unit table;
-- or return false, t where t is an error message table.
-- The returned input unit table may be for a fake unit using the specified
-- MediaWiki removes leading and trailing whitespace from the values of
-- unit code as the symbol and name, and with bad_mcode = message code table.
-- named arguments. However, the values of numbered arguments include any
-- whitespaceMediaWiki enteredremoves inleading theand template, andtrailing whitespace isfrom usedthe byvalues someof
-- named arguments. However, the values of numbered arguments include any
-- parameters (example: the numbered parameters associated with "disp=x").
-- whitespace entered in the template, and whitespace is used by some
local parms = {} -- arguments passed to template
-- parameters (example: the numbered parameters associated with "disp=x").
local named_keys = collection() -- numbered table of named keys in parms: needed because cannot iterate parms and add new fields to it
local parms = {} -- arguments passed to template, after translation
for k, v in pairs(pframe.args) do
local kv_pairs = {} -- table of input key:value pairs where key is a name; needed because cannot iterate parms and add new fields to it
parms[k] = v
for k, v in pairs(pframe.args) do
if type(k) == 'string' then
if type(k) == 'number' or k == 'test' then -- parameter "test" is reserved for testing and is not translated
named_keys:add(k)
parms[k] = v
end
else
end
kv_pairs[k] = v
local success, msg = translate_parms(parms, named_keys)
end
if not success then return false, msg end
end
local success, valinfo, i = get_values(parms)
local success, msg = translate_parms(parms, kv_pairs)
if not success then return false, valinfo end
if not success then return false, msg end
local in_unit = strip(parms[i])
local success, valinfo, i, in_unit, in_unit_table = simple_get_values(parms)
i = i + 1
if not success then
local success, in_unit_table = lookup(in_unit, parms.opt_sp_us, 'no_combination')
success, valinfo, i = get_values(parms)
if not success then return false, in_unit_table end
if not success then return false, valinfo end
if parms.test == 'msg' then
in_unit = strip(parms[i])
-- Am testing the messages produced when no output unit is specified, and
i = i + 1
-- the input unit has a missing or invalid default.
success, in_unit_table = lookup(in_unit, parms.opt_sp_us, 'no_combination')
-- Set two units for testing that.
if not success then
-- LATER: Remove this code.
if in_unit == 'chain'nil then
in_unit = ''
in_unit_table.default = nil -- no default
end
elseif in_unit == 'rd' then
if parms.opt_ignore_error then -- display given unit code with no error (for use with {{val}})
in_unit_table.default = "ft!X!m" -- an invalid expression
in_unit_table = '' -- suppress error message and prevent processing of output unit
end
end
in_unit_table = setmetatable({ symbol = in_unit, name2 = in_unit,
in_unit_table.valinfo = valinfo
default = "m", defkey = "m", linkey = "m",
in_unit_table.inout = 'in' -- this is an input unit
utype = "length", scale = 1, bad_mcode = in_unit_table }, unit_mt)
if not parms.range then
end
local success, inext, composite_unit = get_composite(parms, i, valinfo[1].value, in_unit_table)
end
if not success then return false, inext end
if parms.test == 'msg' then
if composite_unit then
-- Am testing the messages produced when no output unit is specified, and
in_unit_table = composite_unit
-- the input unit has a missing or invalid default.
i = inext
-- Set two units for testing that.
end
-- LATER: Remove this code.
end
if in_unit_table.builtinin_unit == 'machchain' then
in_unit_table.default = nil -- no default
-- As with old template, a number following Mach as the input unit is the altitude,
elseif in_unit == 'rd' then
-- and there is no way to specify an altitude for the output unit.
in_unit_table.default = "ft!X!m" -- an invalid expression
-- Could put more code in this function to get any output unit and check for
end
-- an altitude following that unit.
end
local success, info = extract_number(parms, parms[i], false, true)
in_unit_table.valinfo = valinfo
if success then
in_unit_table.inout = 'in' -- this is an input unit
i = i + 1
if not parms.range then
in_unit_table.altitude = info.value
local success, inext, composite_unit = get_composite(parms, i, valinfo[1].value, in_unit_table)
end
if not success then return false, inext end
end
if composite_unit then
local next = strip(parms[i])
in_unit_table = composite_unit
i = i + 1
i = inext
local precision, is_bad_precision
end
local function set_precision(text)
end
local number, is_integer = get_number(text)
if in_unit_table.builtin == 'mach' then
if number then
-- As with old template, a number following Mach as the input unit is the altitude,
if is_integer then
-- and there is no way to specify an altitude for the output unit.
precision = number
-- Could put more code in this function to get any output unit and check for
else
-- an altitude following that unit.
precision = text
local success, info = extract_number(parms, parms[i], false, true)
is_bad_precision = true
if success then
end
i = i + 1
return true -- text was used for precision, good or bad
in_unit_table.altitude = info.value
end
end
end
if not set_precision(next) then
local next = strip(parms[i])
parms.out_unit = next
i = i + 1
if set_precision(strip(parms[i])) then
local precision, is_bad_precision
i = i + 1
local function set_precision(text)
end
local number, is_integer = get_number(text)
end
if parms.opt_adj_midnumber then
if is_integer then
parms.opt_adjectival = true
precision = number
next = parms[i]
else
i = i + 1
precision = text
if next then -- mid-text words
is_bad_precision = true
if next:sub(1, 1) == '-' then
end
parms.mid = next
return true -- text was used for precision, good or bad
else
end
parms.mid = ' ' .. next
end
end
if not set_precision(next) then
end
parms.out_unit = next
end
if set_precision(strip(parms.opt_one_preunit[i])) then
i = i + 1
parms[parms.opt_flip and 'preunit2' or 'preunit1'] = preunits(1, parms[i])
end
i = i + 1
end
if parms.disp == 'x'opt_adj_mid then
next = parms[i]
-- Following is reasonably compatible with the old template.
i = i + 1
local first = parms[i] or ''
if next then -- mid-text words
local second = parms[i+1] or ''
if next:sub(1, 1) == '-' then
i = i + 2
parms.mid = next
if strip(first) == '' then -- user can enter '&#32;' rather than ' ' to avoid the default
else
first = ' [&nbsp;' .. first
second parms.mid = '&nbsp;] ' .. secondnext
end
end
parms.joins = { first, second }
end
elseif parms.opt_two_preunits then
if parms.opt_one_preunit then
local p1, p2 = preunits(2, parms[i], parms[i+1])
parms[parms.opt_flip and 'preunit2' or 'preunit1'] = preunits(1, parms[i])
i = i + 2
i = i + 1
if parms.preunit1 then
end
-- To simplify documentation, allow unlikely use of adj=pre with disp=preunit
if parms.disp == 'x' then
-- (however, an output unit must be specified with adj=pre and with disp=preunit).
-- Following is reasonably compatible with the old template.
parms.preunit1 = parms.preunit1 .. p1
local first = parms.preunit2[i] =or p2''
local second = parms[i+1] or ''
else
i = i + 2
parms.preunit1, parms.preunit2 = p1, p2
if strip(first) == '' then -- user can enter '&#32;' rather than ' ' to avoid the default
end
first = ' [&nbsp;' .. first
end
second = '&nbsp;]' .. second
if precision == nil then
end
if set_precision(strip(parms[i])) then
parms.joins = { first, second }
i = i + 1
elseif parms.opt_two_preunits then
end
local p1, p2 = preunits(2, parms[i], parms[i+1])
end
i = i + 2
if is_bad_precision then
if parms.preunit1 then
return false, { 'cvt_bad_prec', precision }
-- To simplify documentation, allow unlikely use of adj=pre with disp=preunit
end
-- (however, an output unit must be specified with adj=pre and with disp=preunit).
parms.precision = precision
parms.preunit1 = parms.preunit1 .. p1
return true, parms, in_unit_table
parms.preunit2 = p2
else
parms.preunit1, parms.preunit2 = p1, p2
end
end
if precision == nil then
if set_precision(strip(parms[i])) then
i = i + 1
end
end
if is_bad_precision then
add_warning(parms, 1, 'cvt_bad_prec', precision)
else
parms.precision = precision
end
return true, parms, in_unit_table
end
 
local function default_precisionrecord_default_precision(invalue, inclean, outvalue, in_currentparms, out_current, extraprecision)
-- If necessary, adjust parameters and return a possibly adjusted precision.
-- Return a default value for precision (an integer like 2, 0, -2).
-- When converting a range of values where a default precision is required,
-- Code follows procedures used in old template.
-- that default is calculated for each value because the result sometimes
local fudge = 1e-14 -- {{Order of magnitude}} adds this, so we do too
-- depends on the precise input and output values. This function may cause
local prec, minprec, adjust
-- the entire convert process to be repeated in order to ensure that the
local utype = out_current.utype
-- same default precision is used for each individual convert.
local subunit_ignore_trailing_zero
-- If that were not done, a range like 1000 to 1000.4 may give poor results
local subunit_more_precision -- kludge for "in" used in input like "|2|ft|6|in"
-- because the first output could be heavily rounded, while the second is not.
local composite = in_current.composite
-- For range 1000.4 to 1000, this function can give the second convert the
if composite then
-- same default precision that was used for the first.
subunit_ignore_trailing_zero = true -- input "|2|st|10|lb" has precision 0, not -1
if not parms.opt_round_each then
if composite[#composite].exception == 'subunit_more_precision' then
local maxdef = out_current.max_default_precision
subunit_more_precision = true -- do not use standard precision with input like "|2|ft|6|in"
if maxdef then
end
if maxdef < precision then
end
parms.do_convert_again = true
-- Count digits after decimal mark, handling cases like '12.345e6'.
out_current.max_default_precision = precision
local exponent
else
local integer, dot, fraction, expstr = inclean:match('^(%d*)(%.?)(%d*)(.*)')
precision = out_current.max_default_precision
local e = expstr:sub(1, 1)
end
local boost = 0 -- can increase default precision
else
if e == 'e' or e == 'E' then
out_current.max_default_precision = precision
exponent = tonumber(expstr:sub(2))
end
elseif expstr:find('/', 1, true) then
end
boost = 1 -- any input fraction is regarded as one extra digit of precision
return precision
end
if dot == '' then
prec = subunit_ignore_trailing_zero and 0 or -integer:match('0*$'):len()
else
prec = #fraction
end
if exponent then
-- So '1230' and '1.23e3' both give prec = -1, and '0.00123' and '1.23e-3' give 5.
prec = prec - exponent
end
local exception = (utype == 'temperature' and not
(in_current.exception == 'temperature' or out_current.exception == 'temperature'))
if exception then
-- Kelvin value can be almost zero, or small but negative due to precision problems.
-- Also, an input value like -300 C (below absolute zero) gives negative kelvins.
-- Calculate minimum precision from absolute value.
adjust = 0
local kelvin = abs((invalue - in_current.offset) * in_current.scale)
if kelvin < 1e-8 then -- assume nonzero due to input or calculation precision problem
minprec = 2
else
minprec = 2 - floor(log10(kelvin) + fudge) -- 3 sigfigs in kelvin
end
else
if invalue == 0 or outvalue <= 0 then
-- We are never called with a negative outvalue, but it might be zero.
-- This is special-cased to avoid calculation exceptions.
return 0
end
if out_current.exception == 'integer_more_precision' and floor(invalue) == invalue then
-- With certain output units that sometimes give poor results
-- with default rounding, use more precision when the input
-- value is equal to an integer. An example of a poor result
-- is when input 50 gives a smaller output than input 49.5.
-- Experiment shows this helps, but it does not eliminate all
-- surprises because it is not clear whether "50" should be
-- interpreted as "from 45 to 55" or "from 49.5 to 50.5".
adjust = -log10(in_current.scale)
elseif subunit_more_precision then
-- Conversion like "{{convert|6|ft|1|in|cm}}" (where subunit is "in")
-- has a non-standard adjust value, to give more output precision.
adjust = log10(out_current.scale) + 2
else
adjust = log10(abs(invalue / outvalue))
end
adjust = adjust + log10(2)
-- Ensure that the output has at least two significant figures.
minprec = 1 - floor(log10(outvalue) + fudge)
end
if extra then
adjust = extra.adjust or adjust
minprec = extra.minprec or minprec
end
return math.max(floor(prec + adjust + boost), minprec)
end
 
local function convertdefault_precision(parms, invalue, inclean, denominator, outvalue, in_current, out_current, extra)
-- ConvertReturn givena inputdefault value fromfor oneprecision unit(an tointeger anotherlike 2, 0, -2).
-- If denominator is not nil, it is the value of the denominator in inclean.
-- Return output_value (a number) if a simple convert, or
-- Code follows procedures used in old template.
-- return f, t where
local fudge = 1e-14 -- {{Order of magnitude}} adds this, so we do too
-- f = true, t = table of information with results, or
local prec, minprec, adjust
-- f = false, t = error message table.
local inscaleutype = in_currentout_current.scaleutype
local subunit_ignore_trailing_zero
local outscale = out_current.scale
local subunit_more_precision -- kludge for "in" used in input like "|2|ft|6|in"
if not in_current.iscomplex and not out_current.iscomplex then
local composite = in_current.composite
return invalue * (inscale / outscale) -- minimize overhead for most common case
if composite then
end
subunit_ignore_trailing_zero = true -- input "|2|st|10|lb" has precision 0, not -1
if in_current.invert then
if composite[#composite].exception == 'subunit_more_precision' then
-- Fuel efficiency (there are no built-ins for this type of unit).
subunit_more_precision = true -- do not use standard precision with input like "|2|ft|6|in"
if in_current.invert * out_current.invert < 0 then
end
return 1 / (invalue * inscale * outscale)
end
if denominator and denominator > 0 then
return invalue * (inscale / outscale)
prec = math.max(log10(denominator), 1)
elseif in_current.offset then
else
-- Temperature (there are no built-ins for this type of unit).
-- Count digits after decimal mark, handling cases like '12.345e6'.
return (invalue - in_current.offset) * (inscale / outscale) + out_current.offset
local exponent
else
local integer, dot, decimals, expstr = inclean:match('^(%d*)(%.?)(%d*)(.*)')
-- Built-in unit.
local e = expstr:sub(1, 1)
local in_builtin = in_current.builtin
if e == 'e' or e == 'E' then
local out_builtin = out_current.builtin
exponent = tonumber(expstr:sub(2))
if in_builtin and out_builtin then
end
if in_builtin == out_builtin then
if dot == '' then
return invalue
prec = subunit_ignore_trailing_zero and 0 or -integer:match('0*$'):len()
end
else
-- There are no cases (yet) where need to convert from one
prec = #decimals
-- built-in unit to another, so this should never occur.
end
return false, { 'cvt_bug_convert' }
if exponent then
end
-- So '1230' and '1.23e3' both give prec = -1, and '0.00123' and '1.23e-3' give 5.
if in_builtin == 'mach' or out_builtin == 'mach' then
prec = prec - exponent
local adjust
end
if in_builtin == 'mach' then
end
inscale = speed_of_sound(in_current.altitude)
if in_current.istemperature and out_current.istemperature then
adjust = outscale / 0.1
-- Converting between common temperatures (°C, °F, °R, K); not keVT, MK.
else
-- Kelvin value can be almost zero, or small but negative due to precision problems.
outscale = speed_of_sound(out_current.altitude)
-- Also, an input value like -300 C (below absolute zero) gives negative kelvins.
adjust = 0.1 / inscale
-- Calculate minimum precision from absolute value.
end
adjust = 0
return true, {
local kelvin = abs((invalue - in_current.offset) * in_current.scale)
outvalue = invalue * (inscale / outscale),
if kelvin < 1e-8 then -- assume nonzero due to input or calculation precision problem
adjust = log10(adjust) + log10(2),
minprec = 2
}
else
elseif in_builtin == 'hand' then
minprec = 2 - floor(log10(kelvin) + fudge) -- 3 sigfigs in kelvin
-- 1 hand = 4 inches; 1.2 hands = 6 inches.
end
-- Fractions of a hand are only defined for the first digit, and
else
-- the first fractional digit should be a number of inches (1, 2 or 3).
if invalue == 0 or outvalue <= 0 then
-- However, this code interprets the entire fraction as the number
-- We are never called with a negative outvalue, but it might be zero.
-- of inches / 10 (so 1.75 inches would be 0.175 hands).
-- This is special-cased to avoid calculation exceptions.
-- A value like 12.3 hands is exactly 12*4 + 3 inches; base default precision on that.
return record_default_precision(parms, out_current, 0)
local integer, fraction = math.modf(invalue)
end
local outvalue = (integer + 2.5 * fraction) * (inscale / outscale)
if out_current.exception == 'integer_more_precision' and floor(invalue) == invalue then
local inch_value = 4 * integer + 10 * fraction -- equivalent number of inches
-- With certain output units that sometimes give poor results
local fracstr = inclean:match('%.(.*)') or ''
-- with default rounding, use more precision when the input
local fmt
-- value is equal to an integer. An example of a poor result
if fracstr == '' then
-- is when input 50 gives a smaller output than input 49.5.
fmt = '%.0f'
-- Experiment shows this helps, but it does not eliminate all
else
-- surprises because it is not clear whether "50" should be
fmt = '%.' .. format('%d', #fracstr - 1) .. 'f'
-- interpreted as "from 45 to 55" or "from 49.5 to 50.5".
end
adjust = -log10(in_current.scale)
return true, {
elseif subunit_more_precision then
invalue = inch_value,
-- Conversion like "{{convert|6|ft|1|in|cm}}" (where subunit is "in")
inclean = format(fmt, inch_value),
-- has a non-standard adjust value, to give more output precision.
outvalue = outvalue,
adjust = log10(out_current.scale) + 2
minprec = 0,
else
}
adjust = log10(abs(invalue / outvalue))
end
end
adjust = adjust + log10(2)
return false, { 'cvt_bug_convert' } -- should never occur
-- Ensure that the output has at least two significant figures.
minprec = 1 - floor(log10(outvalue) + fudge)
end
if extra then
adjust = extra.adjust or adjust
minprec = extra.minprec or minprec
end
return record_default_precision(parms, out_current, math.max(floor(prec + adjust), minprec))
end
 
local function convert(parms, invalue, info, in_current, out_current)
-- Convert given input value from one unit to another.
-- Return output_value (a number) if a simple convert, or
-- return f, t where
-- f = true, t = table of information with results, or
-- f = false, t = error message table.
local inscale = in_current.scale
local outscale = out_current.scale
if not in_current.iscomplex and not out_current.iscomplex then
return invalue * (inscale / outscale) -- minimize overhead for most common case
end
if in_current.invert or out_current.invert then
-- Inverted units, such as inverse length, inverse time, or
-- fuel efficiency. Built-in units do not have invert set.
if (in_current.invert or 1) * (out_current.invert or 1) < 0 then
return 1 / (invalue * inscale * outscale)
end
return invalue * (inscale / outscale)
elseif in_current.offset then
-- Temperature (there are no built-ins for this type of unit).
if info.is_change then
return invalue * (inscale / outscale)
end
return (invalue - in_current.offset) * (inscale / outscale) + out_current.offset
else
-- Built-in unit.
local in_builtin = in_current.builtin
local out_builtin = out_current.builtin
if in_builtin and out_builtin then
if in_builtin == out_builtin then
return invalue
end
-- There are no cases (yet) where need to convert from one
-- built-in unit to another, so this should never occur.
return false, { 'cvt_bug_convert' }
end
if in_builtin == 'mach' or out_builtin == 'mach' then
local adjust
if in_builtin == 'mach' then
inscale = speed_of_sound(in_current.altitude)
adjust = outscale / 0.1
else
outscale = speed_of_sound(out_current.altitude)
adjust = 0.1 / inscale
end
return true, {
outvalue = invalue * (inscale / outscale),
adjust = log10(adjust) + log10(2),
}
elseif in_builtin == 'hand' then
-- 1 hand = 4 inches; 1.2 hands = 6 inches.
-- Decimals of a hand are only defined for the first digit, and
-- the first fractional digit should be a number of inches (1, 2 or 3).
-- However, this code interprets the entire fractional part as the number
-- of inches / 10 (so 1.75 inches would be 0.175 hands).
-- A value like 12.3 hands is exactly 12*4 + 3 inches; base default precision on that.
local integer, fracpart = math.modf(invalue)
local inch_value = 4 * integer + 10 * fracpart -- equivalent number of inches
local factor = inscale / outscale
if factor == 4 then
-- Am converting to inches: show exact result, and use "inches" not "in" by default.
if parms.abbr_org == nil then
out_current.usename = true
end
local show = format('%g', abs(inch_value)) -- show and clean are unsigned
if not show:find('e', 1, true) then
return true, {
invalue = inch_value,
outvalue = inch_value,
clean = show,
show = show,
}
end
end
local outvalue = (integer + 2.5 * fracpart) * factor
local fracstr = info.clean:match('%.(.*)') or ''
local fmt
if fracstr == '' then
fmt = '%.0f'
else
fmt = '%.' .. format('%d', #fracstr - 1) .. 'f'
end
return true, {
invalue = inch_value,
clean = format(fmt, inch_value),
outvalue = outvalue,
minprec = 0,
}
end
end
return false, { 'cvt_bug_convert' } -- should never occur
end
 
local cvt_to_hand
 
local function cvtround(parms, info, in_current, out_current)
-- Return true, t where t is a table with the conversion results; fields:
-- show = rounded, formatted string with the result of 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";
-- (and more fields shown below, and a calculated 'absvalue' field).
-- or return true, nil if no value specified;
-- or return false, t where t is an error message table.
-- Input info.clean uses en digits (it has been translated, if necessary).
-- Output show uses en or non-en digits as appropriate, or can be spelled.
local invalue, inclean, show, exponent, singular
if info then
invalue, inclean = info.value, info.clean
if in_current.builtin == 'hand' then
end
invalue = info.altvalue
if invalue == nil or invalue == '' then
end
return true, nil
end
if invalue == nil ifor out_current.builtininvalue == 'hand' then
return true, nil
-- Convert to hands, then convert the fractional part to inches.
end
-- Code is not correct when output is spelled, and it ignores any requested
if out_current.builtin == 'hand' then
-- precision if the output uses scientific notation (very large, or very
return cvt_to_hand(parms, info, in_current, out_current)
-- small). Not worth more complexity as these cases should be very rare.
end
local dummy_unit_table = { scale = out_current.scale }
local successoutvalue, outinfoextra = cvtroundconvert(parms, invalue, info, in_current, dummy_unit_tableout_current)
if extra then
if not success then return false, outinfo end
if not outvalue then return false, extra end
local fmt
invalue = extra.invalue or invalue
if outinfo.is_scientific then
outvalue = extra.outvalue
fmt = '%.1f'
end
else
if not valid_number(outvalue) then
local fraction = (outinfo.show):match('[' .. numdot .. '](.*)') or '' -- outinfo.show is in local language
return false, { 'cvt_invalid_num' }
if fraction == '' then
end
if not outinfo.use_default_precision then
local isnegative
return true, outinfo
if outvalue < 0 then
end
isnegative = true
fmt = '%.0f'
outvalue = -outvalue
else
end
fmt = '%.' .. format('%d', ulen(fraction) - 1) .. 'f'
local numerator, precision, success, show, exponent
end
local denominator = out_current.frac
end
if denominator then
local hands, inches = math.modf(outinfo.raw_absvalue)
show = fraction_table(outvalue, denominator)
inches = format(fmt, inches * 4)
else
if inches:sub(1, 1) == '4' then
precision = parms.precision
hands = hands + 1
if not precision then
inches = '0' .. inches:sub(2)
local sigfig = parms.sigfig
if tonumber(inches) == 0 then
if sigfig then
inches = '0'
show, exponent = make_sigfig(outvalue, sigfig)
end
elseif parms.opt_round5 or parms.opt_round25 then
end
local n = parms.opt_round5 and 5 or 25
if inches:sub(2, 2) == '.' then
show = format('%.0f', floor((outvalue / n) + 0.5) * n)
inches = inches:sub(1, 1) .. inches:sub(3)
else
end
local inclean = info.clean
return true, {
if extra then
sign = outinfo.sign,
inclean = extra.clean or inclean
singular = outinfo.singular,
show = extra.show
show = outinfo.sign .. with_separator(parms, format('%d', hands)) .. numdot .. from_en(inches)
end
}
if not show then
end
local outvalue, extra precision = convertdefault_precision(parms, invalue, inclean, info.denominator, outvalue, in_current, out_current, extra)
end
if extra then
end
if not outvalue then return false, extra end
end
invalue = extra.invalue or invalue
end
inclean = extra.inclean or inclean
if precision then
outvalue = extra.outvalue
if precision >= 0 then
end
local fudge
if not valid_number(outvalue) then
if precision <= 8 then
return false, { 'cvt_invalid_num' }
-- Add a fudge to handle common cases of bad rounding due to inability
end
-- to precisely represent some values. This makes the following work:
local isnegative
-- {{convert|-100.1|C|K}} and {{convert|5555000|um|m|2}}.
if outvalue < 0 then
-- Old template uses #expr round, which invokes PHP round().
isnegative = true
-- LATER: Investigate how PHP round() works.
outvalue = -outvalue
fudge = 2e-14
end
else
local success, use_default_precision
fudge = 0
local precision = parms.precision
end
if not precision then
local fmt = '%.' .. format('%d', precision) .. 'f'
local sigfig = parms.sigfig
local success
if sigfig then
success, show = pcall(format, fmt, outvalue + fudge)
show, exponent = make_sigfig(outvalue, sigfig)
if not success then
elseif parms.opt_round5 then
return false, { 'cvt_big_prec', tostring(precision) }
show = format('%.0f', floor((outvalue / 5) + 0.5) * 5)
end
else
else
use_default_precision = true
precision = -precision -- #digits to zero (in addition to any digits after dot)
precision = default_precision(invalue, inclean, outvalue, in_current, out_current, extra)
local shift = 10 ^ precision
end
show = format('%.0f', outvalue/shift)
end
if show ~= if precision'0' then
exponent = #show if+ precision >= 0 then
end
if precision <= 8 then
end
-- Add a fudge to handle common cases of bad rounding due to inability
end
-- to precisely represent some values. This makes the following work:
local t = format_number(parms, show, exponent, isnegative)
-- {{convert|-100.1|C|K}} and {{convert|5555000|um|m|2}}.
-- Set singular using match because on some systems 0.99999999999999999 is 1.0.
-- Old template uses #expr round, which invokes PHP round().
t.singular = (type(show) == 'string' and (show == '1' or show:match('^1%.0*$') ~= nil) and not isnegative)
-- LATER: Investigate how PHP round() works.
t.fraction_table = (type(show) == 'table') and show or nil
outvalue = outvalue + 2e-14
t.raw_absvalue = outvalue -- absolute value before rounding
end
return true, setmetatable(t, {
local fmt = '%.' .. format('%d', precision) .. 'f'
__index = function (self, key)
local success
if key == 'absvalue' then
success, show = pcall(format, fmt, outvalue)
-- Calculate absolute value after rounding, if needed.
if not success then
local clean, exponent = rawget(self, 'clean'), rawget(self, 'exponent')
return false, { 'cvt_big_prec', tostring(precision) }
local value = tonumber(clean) -- absolute value (any negative sign has been ignored)
end
if exponent then
else
value = value * 10^exponent
precision = -precision -- #digits to zero (in addition to any digits after dot)
end
local shift = 10 ^ precision
rawset(self, key, value)
show = format('%.0f', outvalue/shift)
return value
if show ~= '0' then
end
exponent = #show + precision
end })
end
end
 
end
function cvt_to_hand(parms, info, in_current, out_current)
if (show == '1' or show:match('^1%.0*$') ~= nil) and not isnegative then
-- Convert input to hands, inches.
-- Use match because on some systems 0.99999999999999999 is 1.0.
-- Return true, t where t is a table with the conversion results;
singular = true
-- or return false, t where t is an error message table.
end
if parms.abbr_org == nil then
local t = format_number(parms, show, exponent, isnegative)
out_current.usename = true -- default is to show name not symbol
t.singular = singular
end
t.raw_absvalue = outvalue -- absolute value before rounding
local precision = parms.precision
t.use_default_precision = use_default_precision
local frac = out_current.frac
return true, setmetatable(t, {
if not frac and precision and precision > 1 then
__index = function (self, key)
frac = (precision == 2) and 2 or 4
if key == 'absvalue' then
end
-- Calculate absolute value after rounding, if needed.
local out_next = out_current.out_next
local clean, exponent = rawget(self, 'clean'), rawget(self, 'exponent')
if out_next then
local value = tonumber(clean) -- absolute value (any negative sign has been ignored)
-- Use magic knowledge to determine whether the next unit is inches without requiring i18n.
if exponent then
-- The following ensures that when the output combination "hand in" is used, the inches
value = value * 10^exponent
-- value is rounded to match the hands value. Also, displaying say "61½" instead of 61.5
end
-- is better as 61.5 implies the value is not 61.4.
rawset(self, key, value)
if out_next.exception == 'subunit_more_precision' then
return value
out_next.frac = frac
end
end })
end
-- Convert to inches; calculate hands from that.
local dummy_unit_table = { scale = out_current.scale / 4, frac = frac }
local success, outinfo = cvtround(parms, info, in_current, dummy_unit_table)
if not success then return false, outinfo end
local tfrac = outinfo.fraction_table
local inches = outinfo.raw_absvalue
if tfrac then
inches = floor(inches) -- integer part only; fraction added later
else
inches = floor(inches + 0.5) -- a hands measurement never shows decimals of an inch
end
local hands, inches = divide(inches, 4)
outinfo.absvalue = hands + inches/4 -- supposed to be the absolute rounded value, but this is close enough
local inchstr = tostring(inches) -- '0', '1', '2' or '3'
if precision and precision <= 0 then -- using negative or 0 for precision rounds to nearest hand
hands = floor(outinfo.raw_absvalue/4 + 0.5)
inchstr = ''
elseif tfrac then
-- Always show an integer before fraction (like "15.0½") because "15½" means 15-and-a-half hands.
inchstr = numdot .. format_fraction(parms, 'out', false, inchstr, tfrac.numstr, tfrac.denstr)
else
inchstr = numdot .. from_en(inchstr)
end
outinfo.show = outinfo.sign .. with_separator(parms, format('%.0f', hands)) .. inchstr
return true, outinfo
end
 
local function evaluate_condition(value, condition)
-- Return true or false from applying a conditional expression to value,
-- or throw an error if invalid.
-- A very limited set of expressions is supported:
-- v < 9
-- v * 9 < 9
-- where
-- 'v' is replaced with value
-- 9 is any number (as defined by Lua tonumber)
-- only en digits are accepted
-- '<' can also be '<=' or '>' or '>='
-- In addition, the following form is supported:
-- LHS and RHS
-- where
-- LHS, RHS = any of above expressions.
local function compare(value, text)
local arithop, factor, compop, limit = text:match('^%s*v%s*([*]?)(.-)([<>]=?)(.*)$')
if arithop == nil then
error('Invalid default expression', 0)
elseif arithop == '*' then
factor = tonumber(factor)
if factor == nil then
error('Invalid default expression', 0)
end
end
value = value * factor
end
limit = tonumber(limit)
if limit == nil then
error('Invalid default expression', 0)
end
if compop == '<' then
return value < limit
elseif compop == '<=' then
return value <= limit
elseif compop == '>' then
return value > limit
elseif compop == '>=' then
return value >= limit
end
error('Invalid default expression', 0) -- should not occur
end
local lhs, rhs = condition:match('^(.-%W)and(%W.*)')
if lhs == nil then
return compare(value, condition)
end
return compare(value, lhs) and compare(value, rhs)
end
 
local function get_default(value, unit_table)
-- Return true, s where s = name of unit's default output unit,
-- or return false, t where t is an error message table.
-- Some units have a default that depends on the input value
-- (the first value if a range of values is used).
-- If '!' is in the default, the first bang-delimited field is an
-- expression that uses 'v' to represent the input value.
-- Example: 'v < 120 ! small ! big ! suffix' (suffix is optional)
-- evaluates 'v < 120' as a boolean with result
-- 'smallsuffix' if (value < 120), or 'bigsuffix' otherwise.
-- Input must use en digits and '.' decimal mark.
local default = default_exceptions[unit_table.defkey or unit_table.symbol] or unit_table.default
if ifnot default == nil then
return false, { 'cvt_no_default', unit_table.symbol }
end
if default:find('!', 1, true) == nil then
return true, default
end
local t = split(default, '!')
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
end
return true, default
end
end
return false, { 'cvt_bad_default', unit_table.symbol }
end
 
১,৯০৯ ⟶ ২,৩৮১ নং লাইন:
 
local function make_link(link, id, link_key)
-- Return wikilink "[[link|id]]", possibly abbreviated as in examples:
-- [[Mile|mile]] --> [[mile]]
-- [[Mile|miles]] --> [[mile]]s
-- However, just id is returned if:
-- * no link given (so caller does not need to check if a link was defined); or
-- * link has previously been used during the current convert (to avoid overlinking).
-- Linking with a unit uses the unit table as the link key, which fails to detect
-- overlinking for conversions like the following (each links "mile" twice):
-- {{convert|1|impgal/mi|USgal/mi|lk=on}}
-- {{convert|1|l/km|impgal/mi USgal/mi|lk=on}}
link_key = link_key or link -- use key if given (the key, but not the link, may be known when need to cancel a link record)
if ifnot link == nil or link == '' or linked_pages[link_key] then
return id
end
linked_pages[link_key] = true
-- Following only works for language en, but it should be safe on other wikis,
-- and overhead of doing it generally does not seem worthwhile.
local l = link:sub(1, 1):lower() .. link:sub(2)
if link == id or l == id then
return '[[' .. id .. ']]'
elseif link .. 's' == id or l .. 's' == id then
return '[[' .. id:sub(1, -2) .. ']]s'
else
return '[[' .. link .. '|' .. id .. ']]'
end
end
 
local function variable_name(clean, unit_table)
-- For slwiki (Slovenian Wikipedia), a unit name depends on the value.
-- Parameter clean is the unsigned rounded value in en digits, as a string.
-- Value Source Example for "m"
-- integer 1: name1 meter (also is the name of the unit)
-- integer 2: var{1} metra
-- integer 3 and 4: var{2} metri
-- integer else: var{3} metrov (0 and 5 or more)
-- real/fraction: var{4} metra
-- var{i} means the i'th field in unit_table.varname if it exists and has
-- an i'th field, otherwise name2.
-- Fields are separated with "!" and are not empty.
-- A field for a unit using an SI prefix has the prefix name inserted,
-- replacing '#' if found, or before the field otherwise.
local vname
if clean == '1' then
vname = unit_table.name1
elseif unit_table.varname then
local i
if clean == '2' then
i = 1
elseif clean == '3' or clean == '4' then
i = 2
elseif clean:find('.', 1, true) then
i = 4
else
i = 3
end
vname = split(unit_table.varname, '!')[i]
end
if vname then
local si_name = rawget(unit_table, 'si_name') or ''
local pos = vname:find('#', 1, true)
if pos then
vname = vname:sub(1, pos - 1) .. si_name .. vname:sub(pos + 1)
else
vname = si_name .. vname
end
return vname
end
return unit_table.name2
end
 
local function linked_id(unit_table, key_id, want_link, clean)
-- Return final unit id (symbol or name), optionally with a wikilink,
-- and update unit_table.sep if required.
-- key_id is one of: 'symbol', 'sym_us', 'name1', 'name1_us', 'name2', 'name2_us'.
local abbr_on = (key_id == 'symbol' or key_id == 'sym_us')
if abbr_on and want_link then
local symlink = rawget(unit_table, 'symlink')
if symlink then
return symlink -- for exceptions that have the linked symbol built-in
end
end
local multiplier = rawget(unit_table, 'multiplier')
local per = unit_table.per
if per then
local unit1 = per[1] -- top unit_table, or nil
local unit2 = per[2] -- bottom unit_table
if abbr_on then
if not unit1 then
unit_table.sep = '' -- no separator in "$2/acre"
end
end
if not want_link then
local symbol = unit_table.symbol_raw
if symbol then
return symbol -- for exceptions that have the symbol built-in
end
end
end
end
end
local key_id2 -- unit2 is always singular
if key_id == 'name2' then
key_id2 = 'name1'
elseif key_id == 'name2_us' then
key_id2 = 'name1_us'
else
key_id2 = key_id
end
local result
if abbr_on then
result = '/'
elseif unit1 then
result = ' ' .. per_word .. ' '
result = ' per '
else
result = per_word .. ' '
result = 'per '
end
if want_link and if unit1unit_table.link then
if abbr_on or not varname then
result = linked_id(unit1, key_id, want_link) .. result
result = (unit1 and unit1[key_id] or '') .. result .. unit2[key_id2]
end
else
return result .. linked_id(unit2, key_id2, want_link)
result = (unit1 and variable_name(clean, unit1) or '') .. result .. variable_name('1', unit2)
end
end
if multiplier then
return make_link(unit_table.link, result, unit_table)
-- A multiplier (like "100" in "100km") forces the unit to be plural.
end
if abbr_on then
if unit1 then
multiplier = multiplier .. '&nbsp;'
result = linked_id(unit1, key_id, want_link, clean) .. result
else
end
multiplier = multiplier .. ' '
return result .. linked_id(unit2, key_id2, want_link, '1')
if key_id == 'name1' then
end
key_id = 'name2'
if multiplier then
elseif key_id == 'name1_us' then
-- A multiplier (like "100" in "100km") forces the unit to be plural.
key_id = 'name2_us'
multiplier = from_en(multiplier)
end
if abbr_on then
end
multiplier = multiplier .. '&nbsp;'
else
else
multiplier = ''
multiplier = multiplier .. ' '
end
if key_id == 'name1' then
local id = unit_table.fixed_name or unit_table[key_id]
key_id = 'name2'
if want_link then
elseif key_id == 'name1_us' then
local link = link_exceptions[unit_table.symbol] or unit_table.link
key_id = 'name2_us'
if link then
end
local before = ''
end
local i = unit_table.customary
else
if i == 1 and unit_table.sp_us then
multiplier = ''
i = 2 -- show "U.S." not "US"
end
end
local id = unit_table.fixed_name or ((varname and not abbr_on) and variable_name(clean, unit_table) or unit_table[key_id])
if i == 3 and abbr_on then
if want_link then
i = 4 -- abbreviate "imperial" to "imp"
local link = link_exceptions[unit_table.linkey or unit_table.symbol] or unit_table.link
end
if link then
local customary = customary_units[i]
local before = ''
if customary then
local i = unit_table.customary
-- LATER: This works for language en only, but it's esoteric so ignore for now.
if i == 1 and unit_table.sp_us then
local pertext
i = 2 -- show "U.S." not "US"
if id:sub(1, 1) == '/' then
end
-- Want unit "/USgal" to display as "/U.S. gal", not "U.S. /gal".
if i == 3 and abbr_on then
pertext = '/'
i = 4 -- abbreviate "imperial" to "imp"
id = id:sub(2)
end
elseif id:sub(1, 4) == 'per ' then
local customary = text_code.customary_units[i]
-- Similarly want "per U.S. gallon", not "U.S. per gallon" (but in practice this is unlikely to be used).
if customary then
pertext = 'per '
-- LATER: This works for language en only, but it's esoteric so ignore for now.
id = id:sub(5)
local pertext
else
if id:sub(1, 1) == '/' then
pertext = ''
-- Want unit "/USgal" to display as "/U.S. gal", not "U.S. /gal".
end
pertext = '/'
-- Omit any "US"/"U.S."/"imp"/"imperial" from start of id since that will be inserted.
id = id:sub(2)
local removes = (i < 3) and { 'US&nbsp;', 'US ', 'U.S.&nbsp;', 'U.S. ' } or { 'imp&nbsp;', 'imp ', 'imperial ' }
elseif id:sub(1, 4) == 'per ' then
for _, prefix in ipairs(removes) do
-- Similarly want "per U.S. gallon", not "U.S. per gallon" (but in practice this is unlikely to be used).
local plen = #prefix
pertext = 'per '
if id:sub(1, plen) == prefix then
id = id:sub(plen + 15)
else
break
pertext = ''
end
end
end
-- Omit any "US"/"U.S."/"imp"/"imperial" from start of id since that will be inserted.
before = pertext .. make_link(customary.link, customary[1]) .. ' '
local removes = (i < 3) and { 'US&nbsp;', 'US ', 'U.S.&nbsp;', 'U.S. ' } or { 'imp&nbsp;', 'imp ', 'imperial ' }
end
for _, prefix in ipairs(removes) do
id = before .. make_link(link, id, unit_table)
local plen = #prefix
end
if id:sub(1, plen) == prefix then
end
id = id:sub(plen + 1)
return multiplier .. id
break
end
end
before = pertext .. make_link(customary.link, customary[1]) .. ' '
end
id = before .. make_link(link, id, unit_table)
end
end
return multiplier .. id
end
 
local function make_id(parms, which, unit_table)
-- Return id, f where
-- id = unit name or symbol, possibly modified
-- f = true if id is a name, or false if id is a symbol
-- using 1st or 2nd values (which), and for 'in' or 'out' (unit_table.inout).
-- Result is '' if no symbol/name is to be used.
-- In addition, set unit_table.sep = ' ' or '&nbsp;' or ''
-- (the separator that caller will normally insert before the id).
if parms.opt_values then
unit_table.sep = ''
return ''
end
local inout = unit_table.inout
local valinfoinfo = unit_table.valinfo[which]
local abbr_org = parms.abbr_org
local adjectival = parms.opt_adjectival
local disp = parms.disp
local lk = parms.lk
local want_link = (lk == 'on' or lk == inout)
local usename = unit_table.usename
local singularusename = valinfo[which]unit_table.singularusename
local singular = info.singular
if usename then
if usename then
-- Old template does something like this.
-- Old template does something like this.
if lk == 'on' or lk == inout then
if want_link then
-- A linked unit uses the standard singular.
-- A linked unit uses the standard singular.
else
else
-- Set non-standard singular.
-- Set non-standard singular.
local flipped = parms.opt_flip
local flipped = parms.opt_flip
if inout == 'in' then
if inout == 'in' then
if not adjectival and (abbr_org == 'out' or flipped) then
local value = valinfo[which]info.value
singular = (0 < value and value < 1.0001)
end
end
else
if (abbr_org == 'on') or
(not flipped and (abbr_org == nil or abbr_org == 'out')) or
(flipped and abbr_org == 'in') then
singular = (valinfo[which]info.absvalue < 1.0001 and
not valinfo[which]info.is_scientific)
end
end
end
end
end
end
local want_name
if usename then
want_name = true
else
if abbr_org == nil then
if disp == 'br' or disp == 'or' or disp == 'slash' then
want_name = true
end
end
if unit_table.usesymbol then
if unit_table.utype == 'temperature' or unit_table.utype == 'temperature change' then
want_name = false
if not (unit_table.exception == 'temperature') then
end
want_name = false
end
end
if want_name == nil then
end
local abbr = parms.abbr
end
if abbr == 'on' or abbr == inout ifor (abbr == 'mos' and want_nameinout == nil'out') then
want_name = false
local abbr = parms.abbr
else
if abbr == 'on' or abbr == inout or (abbr == 'mos' and inout == 'out') then
want_name = falsetrue
end
else
end
want_name = true
end
end
local key
end
if want_name then
end
if lk == nil and unit_table.builtin == 'hand' then
local key
want_link = true
if want_name then
end
if parms.opt_use_nbsp then
if parms.opt_use_nbsp then
unit_table.sep = '&nbsp;'
unit_table.sep = '&nbsp;'
else
else
unit_table.sep = ' '
unit_table.sep = ' '
end
end
if parms.opt_singular then
if parms.opt_singular then
local value
local value
if inout == 'in' then
if inout == 'in' then
value = valinfo[which].value
value = info.value
else
else
value = valinfo[which].absvalue
value = info.absvalue
end
end
if value then -- some unusual units do not always set value field
if value then -- some unusual units do not always set value = abs(value)field
value = abs(value)
singular = (0 < value and value < 1.0001)
singular = (0 < value and value < 1.0001)
end
end
end
if unit_table.engscale or parms.is_range_x then
if unit_table.engscale or parms.is_range_x then
-- engscale: so "|1|e3kg" gives "1 thousand kilograms" (plural)
-- is_range_xengscale: so "|0.51|x|0.9|mie3kg" gives "0.5 by1 0.9thousand mileskilograms" (plural)
-- is_range_x: so "|0.5|x|0.9|mi" gives "0.5 by 0.9 miles" (plural)
singular = false
singular = false
end
end
key = (adjectival or singular) and 'name1' or 'name2'
key = (adjectival or singular) and 'name1' or 'name2'
if unit_table.sp_us then
if unit_table.sp_us then
key = key .. '_us'
key = key .. '_us'
end
end
else
else
unit_table.sep = '&nbsp;'
key = if unit_table.sp_usbuiltin and== 'sym_ushand' or 'symbol'then
if parms.opt_hand_hh then
end
unit_table.symbol = 'hh' -- LATER: might want i18n applied to this
return linked_id(unit_table, key, lk == 'on' or lk == inout), want_name
end
end
unit_table.sep = '&nbsp;'
key = unit_table.sp_us and 'sym_us' or 'symbol'
end
return linked_id(unit_table, key, want_link, info.clean), want_name
end
 
local function decorate_value(parms, unit_table, which)
-- If needed, update unit_table so values will be shown with extra information.
-- For consistency with the old template (but different from fmtpower),
-- the style to display powers of 10 includes "display:none" to allow some
-- browsers to copy, for example, "10³" as "10^3", rather than as "103".
local info
local engscale = unit_table.engscale
local prefix = unit_table.vprefix
if engscale then
if engscale or prefix then
local inout = unit_table.inout
local info = unit_table.valinfo[which]
if info.decorated then
local abbr = parms.abbr
return -- do not redecorate if repeating convert
if abbr == 'on' or abbr == inout then
end
info.show = info.show ..
info.decorated = true
'<span style="margin-left:0.2em">×<span style="margin-left:0.1em">' ..
end
from_en('10') ..
if engscale then
'</span></span><s style="display:none">^</s><sup>' ..
local inout = unit_table.inout
from_en(tostring(engscale.exponent)) .. '</sup>'
local abbr = parms.abbr
else
if abbr == 'on' or abbr == inout then
local number_id
info.show = info.show ..
local lk = parms.lk
'<span style="margin-left:0.2em">×<span style="margin-left:0.1em">' ..
if lk == 'on' or lk == inout then
from_en('10') ..
number_id = make_link(engscale.link, engscale[1])
'</span></span><s style="display:none">^</s><sup>' ..
else
from_en(tostring(engscale.exponent)) .. '</sup>'
number_id = engscale[1]
else
end
local number_id
-- WP:NUMERAL recommends "&nbsp;" in values like "12 million".
local lk = parms.lk
info.show = info.show .. (parms.opt_adjectival and '-' or '&nbsp;') .. number_id
if lk == 'on' or lk == inout endthen
number_id = make_link(engscale.link, engscale[1])
end
else
local prefix = unit_table.vprefix
number_id = engscale[1]
if prefix then
end
local info = unit_table.valinfo[which]
-- WP:NUMERAL recommends "&nbsp;" in values like "12 million".
info.show = prefix .. info.show
info.show = info.show .. (parms.opt_adjectival and '-' or '&nbsp;') .. number_id
end
end
end
if prefix then
info.show = prefix .. info.show
end
end
 
local function process_input(parms, in_current)
-- Processing required once per conversion.
-- Return block of text to represent input (value/unit).
if parms.opt_output_only or parms.opt_output_number_only or parms.opt_output_unit_only then
parms.joins = { '', '' }
return ''
end
local first_unit
local composite = in_current.composite -- nil or table of units
if composite then
first_unit = composite[1]
else
first_unit = in_current
end
local id1, want_name = make_id(parms, 1, first_unit)
local sep = first_unit.sep -- separator between value and unit, set by make_id
local preunit = parms.preunit1
if preunit then
sep = '' -- any separator is included in preunit
else
preunit = ''
end
if parms.opt_input_unit_only then
parms.joins = { '', '' }
if composite then
local parts = { id1 }
for i, unit in ipairs(composite) do
if i > 1 then
table.insert(parts, (make_id(parms, 1, unit)))
end
end
end
end
id1 = table.concat(parts, ' ')
end
if want_name and parms.opt_adjectival then
return preunit .. hyphenated(id1)
end
return preunit .. id1
end
local abbrdisp_joins = parmstext_code.abbrdisp_joins
local dispabbr = parms.dispabbr
local disp = parms.disp
if disp == nil then -- special case for 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
end
elseif disp == 'sqbr' then
if abbr == 'on' then
disp = 'sqbr-nbsp'
else
disp = 'sqbr-sp'
end
end
end
parms.joins = disp_joins[disp] or disp_joins['b']
end
if parms.opt_also_symbol and not composite then
local join1 = parms.joins[1]
if join1 == ' (' or join1 == ' [' then
parms.joins = { join1 .. first_unit[first_unit.sp_us and 'sym_us' or 'symbol'] .. ', ', parms.joins[2] }
end
end
if in_current.builtin == 'mach' then
local prefix = id1 .. '&nbsp;'
local range = parms.range
local valinfo = first_unit.valinfo
local result = prefix .. valinfo[1].show
if range then
-- For simplicity and because more not needed, handle one range item only.
local prefix2 = make_id(parms, 2, first_unit) .. '&nbsp;'
result = range_text(range[1], want_name, parms, result, prefix2 .. valinfo[2].show)
end
return preunit .. result
end
if composite then
-- Simplify: assume there is no range, and no decoration.
local mid = (not parms.opt_flip) and local parms.mid =or ''
local sep1 = '&nbsp;'
local sep2 = ' '
if parms.opt_adjectival and want_name then
sep1 = '-'
if not parms.opt_flip then
sep2 = '-'
mid = parms.mid or ''
end
end
local parts = { first_unit.valinfo[1].show .. sep1 .. id1 }
if want_name then
for i, unit in ipairs(composite) do
sep1 = '-'
if i > 1 then
sep2 = '-'
table.insert(parts, unit.valinfo[1].show .. sep1 .. (make_id(parms, 1, unit)))
end
end
end
local parts = { first_unit.valinfo[1].show .. sep1 .. id1 }
return table.concat(parts, sep2) .. mid
for i, unit in ipairs(composite) do
end
if i > 1 then
local result, mos
table.insert(parts, unit.valinfo[1].show .. sep1 .. (make_id(parms, 1, unit)))
local range = parms.range
end
if range then
end
mos = (abbr == 'mos')
return table.concat(parts, sep2) .. mid
if not (mos or (parms.is_range_x and not want_name)) then
end
linked_pages[first_unit] = nil -- so the second and only id will be linked, if wanted
local result, mos
end
local range = parms.range
end
if range then
local id = (range == nil) and id1 or make_id(parms, 2, first_unit)
mos = (abbr == 'mos')
local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, 'in')
if not (mos or (parms.is_range_x and not want_name)) then
if mos and was_hyphenated then
linked_pages[first_unit] = nil -- so the second and only id will be linked, if wanted
mos = false -- suppress repeat of unit in a range
end
if linked_pages[first_unit] then
end
linked_pages[first_unit] = nil
local id = (range == nil) and id1 or make_id(parms, 2, first_unit)
id = make_id(parms, 2, first_unit)
local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, 'in')
extra = hyphenated_maybe(parms, want_name, sep, id, 'in')
if mos and was_hyphenated then
end
mos = false -- suppress repeat of unit in a range
end
if linked_pages[first_unit] then
local valinfo = linked_pages[first_unit] = nil.valinfo
if range then
id = make_id(parms, 2, first_unit)
if range.n == 1 then
extra = hyphenated_maybe(parms, want_name, sep, id, 'in')
-- Like {{convert|1|x|2|ft}} (one range item; two values).
end
-- Do what old template did.
end
local valinfosep1 = first_unit.valinfosep
if rangemos then
decorate_value(parms, in_current, 1)
if range.n == 1 then
decorate_value(parms, in_current, 2)
-- Like {{convert|1|x|2|ft}} (one range item; two values).
result = valinfo[1].show .. sep1 .. id1
-- Do what old template did.
elseif parms.is_range_x and not want_name then
local sep1 = first_unit.sep
if abbr == 'in' or abbr == if mos'on' then
decorate_value(parms, in_current, 1)
end
decorate_value(parms, in_current, 2)
decorate_value(parms, in_current, 2)
result = valinfo[1].show .. sep1 .. id1
result = valinfo[1].show .. sep1 .. id1
elseif parms.is_range_x and not want_name then
else
if abbr == 'in' or abbr == 'on' then
if abbr == 'in' or abbr == 'on' then
decorate_value(parms, in_current, 1)
decorate_value(parms, in_current, 1)
end
end
decorate_value(parms, in_current, 2)
decorate_value(parms, in_current, 2)
result = valinfo[1].show .. sep1 .. id1
result = valinfo[1].show
else
end
if abbr == 'in' or abbr == 'on' then
result = range_text(range[1], want_name, parms, result, valinfo[2].show)
decorate_value(parms, in_current, 1)
else
end
-- Like {{convert|1|x|2|x|3|ft}} (two or more range items): simplify.
decorate_value(parms, in_current, 2)
decorate_value(parms, in_current, 1)
result = valinfo[1].show
result = valinfo[1].show
end
for i = 1, range.n do
result = range_text(range[1], want_name, parms, result, valinfo[2].show)
decorate_value(parms, in_current, i+1)
else
result = range_text(range[i], want_name, parms, result, valinfo[i+1].show)
-- Like {{convert|1|x|2|x|3|ft}} (two or more range items): simplify.
end
decorate_value(parms, in_current, 1)
end
result = valinfo[1].show
else
for i = 1, range.n do
decorate_value(parms, in_currentfirst_unit, i+1)
result = range_text(range[i], want_name, parms, result, valinfo[i+1].show)
end
end
return result .. preunit .. extra
end
else
decorate_value(parms, first_unit, 1)
result = valinfo[1].show
end
return result .. preunit .. 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, want_name = make_id(parms, 1, out_current)
local sep = out_current.sep -- set by make_id
local preunit = parms.preunit2
if preunit then
sep = '' -- any separator is included in preunit
else
preunit = ''
end
if parms.opt_output_unit_only then
if want_name and parms.opt_adjectival then
return preunit .. hyphenated(id1)
end
return preunit .. id1
end
if out_current.builtin == 'mach' then
local prefix = id1 .. '&nbsp;'
local range = parms.range
local valinfo = out_current.valinfo
local result = prefix .. valinfo[1].show
if range then
-- For simplicity and because more not needed, handle one range item only.
result = range_text(range[1], want_name, parms, result, prefix .. valinfo[2].show)
end
return preunit .. result
end
local result
local range = parms.range
if range then
if not (parms.is_range_x and not want_name) then
linked_pages[out_current] = nil -- so the second and only id will be linked, if wanted
end
end
local id = (range == nil) and id1 or make_id(parms, 2, out_current)
local extra = hyphenated_maybe(parms, want_name, sep, id, 'out')
local valinfo = out_current.valinfo
if range then
if range.n == 1 then
local sep1 = out_current.sep
local abbr = parms.abbr
if parms.is_range_x and not want_name then
if abbr == 'out' or abbr == 'on' then
decorate_value(parms, out_current, 1)
end
end
decorate_value(parms, out_current, 2)
result = valinfo[1].show .. sep1 .. id1
else
if abbr == 'out' or abbr == 'on' then
decorate_value(parms, out_current, 1)
end
end
decorate_value(parms, out_current, 2)
result = valinfo[1].show
end
end
result = range_text(range[1], want_name, parms, result, valinfo[2].show)
else
-- Like {{convert|1|x|2|x|3|ft}} (two or more range items): simplify.
decorate_value(parms, out_current, 1)
result = valinfo[1].show
for i = 1, range.n do
decorate_value(parms, out_current, i+1)
result = range_text(range[i], want_name, parms, result, valinfo[i+1].show)
end
end
end
else
decorate_value(parms, out_current, 1)
result = valinfo[1].show
end
if parms.opt_output_number_only then
return result
end
return result .. preunit .. extra
end
 
local function make_output_single(parms, in_unit_table, out_unit_table)
-- Return true, item where item = wikitext of the conversion result
-- for a single output (which is not a combination or a multiple);
-- or return false, t where t is an error message table.
out_unit_table.valinfo = collection()
local range = parms.range
for i = 1, (range and (range.n + 1) or 1) do
local success, info = cvtround(parms, in_unit_table.valinfo[i], in_unit_table, out_unit_table)
if not success then return false, info end
out_unit_table.valinfo:add(info)
end
return true, process_one_output(parms, out_unit_table)
end
 
local function make_output_multiple(parms, in_unit_table, out_unit_table)
-- Return true, item where item = wikitext of the conversion result
-- for an output which is a multiple (like 'ftin');
-- or return false, t where t is an error message table.
local multiple = out_unit_table.multiple -- table of scaling factors (will not be nil)
local combos = out_unit_table.combination -- table of unit tables (will not be nil)
local abbr = parms.abbr
local abbr_org = parms.abbr_org
local disp = parms.disp
local want_name = (abbr_org == nil and (disp == 'or' or disp == 'slash')) or
not (abbr == 'on' or abbr == 'out' or abbr == 'mos')
local want_link = (parms.lk == 'on' or parms.lk == 'out')
local mid = parms.opt_flip localand parms.mid =or ''
local sep1 = '&nbsp;'
local sep2 = ' '
if parms.opt_adjectival and want_name then
sep1 = '-'
if parms.opt_flip then
sep2 = '-'
mid = parms.mid or ''
end
local do_spell = parms.opt_spell_out
if want_name then
parms.opt_spell_out = nil -- so the call to cvtround does not spell the value
sep1 = '-'
local function make_result(info, isfirst)
sep2 = '-'
local fmt, outvalue, sign
end
local results = {}
end
for i = 1, #combos do
local function make_result(info)
local fmttfrac, outvaluethisvalue, signstrforce
local resultsout_current = {}combos[i]
out_current.inout = 'out'
for i = 1, #combos do
local scale = multiple[i]
local thisvalue, strforce
if i == 1 then -- least significant unit ('in' from 'ftin')
local out_current = combos[i]
local decimals
out_current.inout = 'out'
out_current.frac = out_unit_table.frac
local scale = multiple[i]
local success, outinfo = cvtround(parms, info, in_unit_table, out_current)
if i == 1 then -- least significant unit ('in' from 'ftin')
if not success then return false, outinfo end
local fraction
if isfirst then
local success, outinfo = cvtround(parms, info, in_unit_table, out_current)
out_unit_table.valinfo = { outinfo } -- in case output value of first least significant unit is needed
if not success then return false, outinfo end
end
sign = outinfo.sign
sign = outinfo.sign
if outinfo.is_scientific then
strforce tfrac = outinfo.showfraction_table
if outinfo.is_scientific then
fraction = ''
strforce = outinfo.show
else
decimals = ''
fraction = (outinfo.show):match('[' .. numdot .. '](.*)') or '' -- outinfo.show is in local language
elseif tfrac then
end
decimals = ''
fmt = '%.' .. ulen(fraction) .. 'f' -- to reproduce precision
else
if fraction == '' then
local show = outinfo.show -- number as a string in local language
outvalue = floor(outinfo.raw_absvalue + 0.5) -- keep all integer digits of least significant unit
local p1, p2 = show:find(numdot, 1, true)
else
decimals = p1 and show:sub(p2 + 1) or '' -- text after numdot, if any
outvalue = outinfo.absvalue
end
end
fmt = '%.' .. ulen(decimals) .. 'f' -- to reproduce precision
end
if decimals == '' then
if scale then
if tfrac then
outvalue, thisvalue = floor(outvalue / scale), outvalue % scale
outvalue = floor(outinfo.raw_absvalue) -- integer part only; fraction added later
else
else
thisvalue = outvalue
outvalue = floor(outinfo.raw_absvalue + 0.5) -- keep all integer digits of least significant unit
end
end
local id
else
if want_name then
outvalue = outinfo.absvalue
id = out_current[(thisvalue == 1) and 'name1' or 'name2']
end
else
end
id = out_current['symbol']
if scale then
end
outvalue, thisvalue = divide(outvalue, scale)
if want_link then
else
local link = out_current.link
thisvalue = outvalue
if link then
end
id = make_link(link, id, out_current)
local id
end
if want_name then
end
if varname then
local strval
local clean
if strforce and outvalue == 0 then
if strforce or tfrac then
sign = '' -- any sign is in strforce
clean = '.1' -- dummy value to force name for floating point
strval = strforce -- show small values in scientific notation; will only use least significant unit
else
strval clean = (thisvalue == 0) and from_en('0') or with_separator(parms, format(fmt, thisvalue))
end
end
id = variable_name(clean, out_current)
table.insert(results, strval .. sep1 .. id)
else
if outvalue == 0 then
local key = 'name2'
break
if parms.opt_adjectival then
end
key = 'name1'
fmt = '%.0f' -- only least significant unit can have a fraction
elseif tfrac then
end
if thisvalue == 0 then
local reversed, count = {}, #results
key = 'name1'
for i = 1, count do
end
reversed[i] = results[count + 1 - i]
elseif parms.opt_singular then
end
if 0 < thisvalue and thisvalue < 1.0001 then
return true, sign .. table.concat(reversed, sep2)
key = 'name1'
end
end
local valinfo = in_unit_table.valinfo
else
local success, result = make_result(valinfo[1])
if thisvalue == 1 then
if not success then return false, result end
key = 'name1'
local range = parms.range
end
if range then
end
for i = 1, range.n do
id = out_current[key]
local success, result2 = make_result(valinfo[i+1])
end
if not success then return false, result2 end
else
result = range_text(range[i], want_name, parms, result, result2)
id = out_current['symbol']
end
end
if want_link then
return true, result .. mid
local link = out_current.link
if link then
id = make_link(link, id, out_current)
end
end
local strval
local inout = (i == #combos or outvalue == 0) and 'out' or '' -- trick so the last value processed (first displayed) has uppercase, if requested
if strforce and outvalue == 0 then
sign = '' -- any sign is in strforce
strval = strforce -- show small values in scientific notation; will only use least significant unit
elseif tfrac then
local wholestr = (thisvalue > 0) and tostring(thisvalue) or nil
strval = format_fraction(parms, inout, false, wholestr, tfrac.numstr, tfrac.denstr, do_spell)
else
strval = (thisvalue == 0) and from_en('0') or with_separator(parms, format(fmt, thisvalue))
if do_spell then
strval = spell_number(parms, inout, strval) or strval
end
end
table.insert(results, strval .. sep1 .. id)
if outvalue == 0 then
break
end
fmt = '%.0f' -- only least significant unit can have a non-integral value
end
local reversed, count = {}, #results
for i = 1, count do
reversed[i] = results[count + 1 - i]
end
return true, sign .. table.concat(reversed, sep2)
end
local valinfo = in_unit_table.valinfo
local success, result = make_result(valinfo[1], true)
if not success then return false, result end
local range = parms.range
if range then
for i = 1, range.n do
local success, result2 = make_result(valinfo[i+1])
if not success then return false, result2 end
result = range_text(range[i], want_name, parms, result, result2)
end
end
return true, result .. mid
end
 
local function process(parms, in_unit_table, out_unit_table)
-- Return true, s where s = final wikitext result,
-- or return false, t where t is an error message table.
linked_pages = {}
local success, out_unit_tablebad_output, out_first
local invalue1bad_input_mcode = in_unit_table.valinfo[1].valuebad_mcode -- false if input unit is valid
local invalue1 = in_unit_table.valinfo[1].value
local out_unit = parms.out_unit
if local out_unit == nil or parms.out_unit == '' then
if out_unit == nil success,or out_unit == get_default(invalue1,'' in_unit_table)then
if bad_input_mcode then
if not success then return false, out_unit end
bad_output = ''
end
else
success, out_unit_table = lookup(out_unit, parms.opt_sp_us, 'any_combination')
success, out_unit = get_default(invalue1, in_unit_table)
if not success then return false, out_unit_table end
parms.out_unit = out_unit
if in_unit_table.utype ~= out_unit_table.utype then
if not success then
return false, { 'cvt_mismatch', in_unit_table.utype, out_unit_table.utype }
bad_output = out_unit
end
end
local flipped = parms.opt_flip
end
local parts = {}
end
for part = 1, 2 do
if not bad_output and not out_unit_table then
-- The LHS (parts[1]) is normally the input, but is the output if flipped.
success, out_unit_table = lookup(out_unit, parms.opt_sp_us, 'any_combination')
-- Process LHS first so it will be linked, if wanted.
if success then
-- Linking to the same item is suppressed in the RHS to avoid overlinking.
local mismatch = check_mismatch(in_unit_table, out_unit_table)
if (part == 1 and not flipped) or (part == 2 and flipped) then
if mismatch then
parts[part] = process_input(parms, in_unit_table)
bad_output = mismatch
else
end
local outputs = {}
else
local combos -- nil (for 'ft' or 'ftin'), or table of unit tables (for 'm ft')
bad_output = out_unit_table
if out_unit_table.multiple == nil then -- nil ('ft' or 'm ft'), or table of factors ('ftin')
end
combos = out_unit_table.combination
end
end
local flipped = parms.opt_flip and not bad_input_mcode
local imax = combos and #combos or 1 -- 1 (single unit) or number of unit tables
local parts = {}
for i = 1, imax do
for part = 1, 2 do
local success, item
-- The LHS (parts[1]) is normally the input, but is the output if flipped.
local out_current = combos and combos[i] or out_unit_table
-- Process LHS first so it will be linked, if wanted.
out_current.inout = 'out'
-- Linking to the same item is suppressed in the RHS to avoid overlinking.
if out_current.multiple == nil then
if (part == 1 and not flipped) or (part == 2 and flipped) then
success, item = make_output_single(parms, in_unit_table, out_current)
parts[part] = process_input(parms, in_unit_table)
else
elseif bad_output then
success, item = make_output_multiple(parms, in_unit_table, out_current)
if bad_output ~= '' then
end
parts[part] = message(bad_output)
if not success then return false, item end
end
table.insert(outputs, item)
else
end
local outputs = {}
parts[part] = parms.opt_input_unit_only and '' or table.concat(outputs, '; ')
local combos -- nil (for 'ft' or 'ftin'), or table of unit tables (for 'm ft')
end
if not out_unit_table.multiple then -- nil/false ('ft' or 'm ft'), or table of factors ('ftin')
end
combos = out_unit_table.combination
if parms.opt_sortable then
end
parts[1] = ntsh(invalue1, parms.opt_sortable_debug) .. parts[1]
local frac = parms.frac -- nil or denominator of fraction for output values
end
if frac then
local wikitext
-- Apply fraction to the unit (if only one), or to non-SI units (if a combination),
if parms.table_joins then
-- except that if a precision is also specified, the fraction only applies to
wikitext = parms.table_joins[1] .. parts[1] .. parms.table_joins[2] .. parts[2]
-- the hand unit; that allows the following result:
else
-- {{convert|156|cm|in hand|1|frac=2}} → 156 centimetres (61.4 in; 15.1½ hands)
wikitext = parts[1] .. parms.joins[1] .. parts[2] .. parms.joins[2]
-- However, the following is handled elsewhere as a special case:
end
-- {{convert|156|cm|hand in|1|frac=2}} → 156 centimetres (15.1½ hands; 61½ in)
if parms.warnings then
if combos then
wikitext = wikitext .. parms.warnings
local precision = parms.precision
end
for _, unit in ipairs(combos) do
return true, wikitext
if unit.builtin == 'hand' or (not precision and not unit.prefixes) then
unit.frac = frac
end
end
else
out_unit_table.frac = frac
end
end
local imax = combos and #combos or 1 -- 1 (single unit) or number of unit tables
for i = 1, imax do
local success, item
local out_current = combos and combos[i] or out_unit_table
out_current.inout = 'out'
if i == 1 then
out_first = out_current
if imax > 1 and out_current.builtin == 'hand' then
out_current.out_next = combos[2] -- built-in hand can influence next unit in a combination
end
end
if out_current.multiple then
success, item = make_output_multiple(parms, in_unit_table, out_current)
else
success, item = make_output_single(parms, in_unit_table, out_current)
end
if not success then return false, item end
table.insert(outputs, item)
end
local sep = parms.table_joins and parms.table_joins[2] or '; '
parts[part] = parms.opt_input_unit_only and '' or table.concat(outputs, sep)
end
end
if parms.opt_sortable_in or parms.opt_sortable_out then
local value
if parms.opt_sortable_in then
value = invalue1
else
local info = out_first and out_first.valinfo
if info then
info = info[1]
value = info.raw_absvalue
if value and info.sign == MINUS then
value = -value
end
end
end
parts[1] = ntsh((value or 0), parms.opt_sortable_debug) .. parts[1]
end
local wikitext
if bad_input_mcode then
if bad_input_mcode == '' then
wikitext = parts[1]
else
wikitext = parts[1] .. message(bad_input_mcode)
end
elseif parms.table_joins then
wikitext = parms.table_joins[1] .. parts[1] .. parms.table_joins[2] .. parts[2]
else
wikitext = parts[1] .. parms.joins[1] .. parts[2] .. parms.joins[2]
end
if parms.warnings and not bad_input_mcode then
wikitext = wikitext .. parms.warnings
end
return true, wikitext, out_unit_table
end
 
local function main_convert(frame)
-- Do convert, and if needed, do it again with higher default precision.
set_config(frame)
set_config(frame)
local result
local result, out_unit_table
local success, parms, in_unit_table = get_parms(frame:getParent())
if success then
for i = 1, 2 do -- use counter so cannot get stuck repeating convert
success, result = process(parms, in_unit_table)
success, result, out_unit_table = process(parms, in_unit_table, out_unit_table)
else
if success and parms.do_convert_again then
result = parms
parms.do_convert_again = false
end
else
if success then
break
return result
end
end
return message(result)
else
result = parms
end
if success then
return result
end
return message(result)
end