跳转到内容

模組:NumberSpell/sandbox

维基百科,自由的百科全书
local getArgs = require('Module:Arguments').getArgs

local p = {}

local max = 100 -- The maximum number that can be parsed.

local ones = {
	[0] = '零',
	[1] = '一',
	[2] = '二',
	[3] = '三',
	[4] = '四',
	[5] = '五',
	[6] = '六',
	[7] = '七',
	[8] = '八',
	[9] = '九'
}

local specials = {
	[10] = '十',
	[11] = '十一',
	[12] = '十二',
	[13] = '十三',
	[14] = '十四',
	[15] = '十五',
	[16] = '十六',
	[17] = '十七',
	[18] = '十八',
	[19] = '十九',
	[20] = '二十',
	[30] = '三十',
	[40] = '四十',
	[50] = '五十',
	[60] = '六十',
	[70] = '七十',
	[80] = '八十',
	[90] = '九十',
	[100] = '一百',
	[200] = '二百',
	[300] = '三百',
	[400] = '四百',
	[500] = '五百',
	[600] = '六百',
	[700] = '七百',
	[800] = '八百',
	[900] = '九百',
	[1000] = '一千',
	[2000] = '二千',
	[3000] = '三千',
	[4000] = '四千',
	[5000] = '五千',
	[6000] = '六千',
	[7000] = '七千',
	[8000] = '八千',
	[9000] = '九千',
	[10000] = '一萬',
	[20000] = '二萬',
	[30000] = '三萬',
	[40000] = '四萬',
	[50000] = '五萬',
	[60000] = '六萬',
	[70000] = '七萬',
	[80000] = '八萬',
	[90000] = '九萬',
}

local formatRules = {
	{num = 90, rule = '九十%s'},
	{num = 80, rule = '八十%s'},
	{num = 70, rule = '七十%s'},
	{num = 60, rule = '六十%s'},
	{num = 50, rule = '五十%s'},
	{num = 40, rule = '四十%s'},
	{num = 30, rule = '三十%s'},
	{num = 20, rule = '二十%s'},
	{num = 10, rule = '十%'}
}

function p.main(frame)
	local args = getArgs(frame)
	local num = tonumber(args[1])
	local success, result = pcall(p._main, num)
	if success then
		return result
	else
		return string.format('<strong class="error">錯誤:%s</strong>', result) -- "result" is the error message.
	end
	return p._main(num)
end

function p._main(num)
	if type(num) ~= 'number' or math.floor(num) ~= num or num < 0 or num > max then
		error('輸入的數值必须是在0與' .. tostring(max), 2 .. '之間的整數')
	end
	-- Check for numbers from 0 to 9.
	local onesVal = ones[num]
	if onesVal then
		return onesVal
	end
	-- Check for special numbers.
	local specialVal = specials[num]
	if specialVal then
		return specialVal
	end
	-- Construct the number from its format rule.
	onesVal = ones[num % 10]
	if not onesVal then
		error('解析' .. tostring(num) .. '這個數的時候發生意外')
	end
	for i, t in ipairs(formatRules) do
		if num >= t.num then
			return string.format(t.rule, onesVal)
		end
	end
	error('在輸入的' .. tostring(num) .. '當中沒有找到規範的格式')
end

return p