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 04:04, 13 May 2023 (automatically remove duplicate units from the output units). 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 ConvertData = require('Module:Convert/data')

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
	
	-- Wipe custom arguments
	convertArgs["default-unit"] = nil
	convertArgs["defaultUnit"] = nil
	convertArgs["default unit"] = nil
	
	-- Remove duplicate units in output units (if available)
	if convertArgs[3] ~= nil then
		local outputUnits = mw.text.split( mw.text.trim( convertArgs[3] ), "%s" )
		local j = 0
		while outputUnits[j] ~= nil do
			if outputUnits[j] == from then
				-- Duplicate unit. Remove it.
				table.remove( outputUnits, j )
				-- Do not increment; the next value will now have an index of `j`.
			else
				j = j + 1
			end
		end
		convertArgs[3] = table.concat( list, " " )
	end
	
	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