Modulo:Conversione/sandbox

Versione del 1 ott 2015 alle 11:58 di Rotpunkt (discussione | contributi) (aggiornato alla versione corrente)
--[[
* 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.name2 or targetunitdata.name1
	elseif args.showunit == 'true' then
		ret = targetunitdata.symbol
	end

	if args.showlink == 'true' then
		link = targetunitdata.link
	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.type ~= targetunitdata.type then
			error('unità di misura incompatibili: ' .. sourceunitdata.type .. ' e ' .. targetunitdata.type)
		end
		val = val * sourceunitdata.scale / targetunitdata.scale
	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