--[[
* Modulo per effettuare la conversione di unità di misura.
*
* Ampiamente modificato a partire da:
* http://fr.wikipedia.org/w/index.php?title=Module:Conversion&oldid=118515752
]]--
require('Modulo:No globals')
local cfg = mw.loadData('Modulo:Conversione/Configurazione')
local p = {}
-- Ritorna il numero arrotondato al numero di cifre decimali richiesto
-- http://lua-users.org/wiki/SimpleRound
local function round(num, idp)
local mult = 10 ^ (idp or 0)
return math.floor(num * mult + 0.5) / mult
end
local function getUnit(val, targetunitdata, args)
local ret, link
if args.showunit == 'long' then
-- unità per esteso
ret = val > 1 and targetunitdata[7] or targetunitdata[6]
elseif args.showunit == 'true' then
ret = targetunitdata[3]
end
if args.showlink == 'true' then
link = targetunitdata[5]
elseif type(args.showlink) == 'string' then
link = args.showlink
end
return ' ' .. (link and '[[' .. link .. '|' .. ret .. ']]' or ret)
end
-- Ritorna il valore convertito alla unità di misura e alle opzioni specificate
function p._main(val, sourceunit, targetunit, args)
local sourceunitdata, targetunitdata, unit, cat
val = tonumber(val)
-- se non è un numero ritorna la stringa non modificata
if not val then
return val
end
if not args then
args = {}
end
if sourceunit and not targetunit then
targetunit = sourceunit
end
sourceunitdata = cfg.units[sourceunit] or cfg.units[cfg.alias[sourceunit]]
targetunitdata = cfg.units[targetunit] or cfg.units[cfg.alias[targetunit]]
if sourceunitdata and targetunitdata then
if sourceunitdata[1] ~= targetunitdata[1] then
error('unità di misura incompatibili: ' .. sourceunitdata[1] .. ' e ' .. targetunitdata[1])
end
val = val * sourceunitdata[2] / targetunitdata[2]
else
cat = '[[Categoria:Pagine con unità di misura non supportata]]'
end
-- eventuale arrotondamento
if args.rounding then
val = round(val, args.rounding)
end
if targetunitdata and (args.showunit == 'true' or args.showunit == 'long') then
unit = getUnit(val, targetunitdata, args)
end
return val .. (unit or '') .. (cat or '')
end
-- Entry-point per {{#invoke:Conversione|main|...}}
function p.main(frame)
local args = frame.args
return p._main(args[1], args[2], args[3], args)
end
return p