Jump to content

Module:Convert default

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Chlod (talk | contribs) at 03:40, 13 May 2023 (change offset). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
local getArgs = require('Module:Arguments').getArgs
local TableTools = require('Module:TableTools')

local p = {}

function p.main(frame)
	local args = getArgs(frame, {
		frameOnly = true,
		trim = true
	})

    return p._main(frame, args)
end

function callConvert( frame, args, input, from )
	local convertArgs = TableTools.shallowClone( args )
	-- Shift all numbered parameters up by 1.
	local i = 2
	while args[i] ~= nil do
		convertArgs[i + 1] = args[i]
		i = i + 1
	end
	-- Set the input value and unit
	convertArgs[1] = input
	convertArgs[2] = from
	return frame:expandTemplate{ title = "convert", args = convertArgs }
end

function p._main(frame, args)
	local rawInput = mw.text.trim( args[1] )
	local defaultUnit = args["default-unit"] or args["defaultUnit"] or args["default unit"];
	
	local numSection = mw.ustring.match( rawInput, "^-?[%d,e]+" )
	if numSection == nil then
		-- Raw output (not a determinable number)
		return rawInput
	end
	
	if mw.ustring.len( rawInput ) == mw.ustring.len( mw.text.trim( numSection ) ) then
		-- There only exists a number section.
		-- Convert, and use the default unit (if defined).
		if not defaultUnit then
			return error("No default unit is set, and a unitless input was provided.")
		else
			return callConvert( frame, args, numSection, defaultUnit )
		end
	else
		-- There exists a text section.
		-- Get that section.
		local textSection = mw.text.trim(
			string.sub( rawInput, mw.ustring.len( mw.text.trim( numSection ) ) + 1 )
		)
		return callConvert( frame, args, numSection, textSection )
	end
end

return p