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:33, 13 May 2023 (creating template for automatic input unit switching based on input parameters). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
local getArgs = require('Module:Arguments').getArgs

local p = {}

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

    return p._main(frame, args)
end

function callConvert( args, input, from )
	local convertArgs = TableTools.shallowClone( args )
	convertArgs[1] = args
	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( 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 ) ) )
		)
		return callConvert( numSection, textSection )
	end
end

return p