มอดูล:ThaiToArabicNum/sandbox

จาก วิกิซอร์ซ

เอกสารการใช้งานสำหรับมอดูลนี้อาจสร้างขึ้นที่ มอดูล:ThaiToArabicNum/sandbox/doc

--[[
	Module for converting Thai number to Arabic number, 
	any other character except Thai number will just passes 
	through the function and comes back as what it came in.
	
	Does Scribunto properly encodes Thai number as input tho?
		Nope, it does not work properly with Thai number input, but works in Arabic number input.
			Found a way to make this work in the main module, keeping this in sandbox for ||phab:phab:T306812||
]]

local p = {} -- Holds functions to be returned from #invoke, and functions to make available to other Lua modules.

--[[
Helper functions used to avoid redundant code.
]]

local function getArgs(frame)
    local args = {}
    for key, value in pairs(frame:getParent().args) do
        args[key] = value
    end
    for key, value in pairs(frame.args) do
        args[key] = value
    end
    return args
end

local function splitChar(inputstr)
    if sep == nil then
        sep = "%s"
    end
    local t = {}
    for str in string.gmatch(inputstr, ".") do
        table.insert(t, str)
    end
    return t
end

-- There's no equivalent of JS' "array.indexOf" ?
local function indexOfTable(t, object)
    if type(t) ~= "table" then error("table expected, got " .. type(t), 2) end

    for i, v in pairs(t) do
        if object == v then
            return i
        end
    end
end

--[[ Now for the main codes ]]
function p.main(frame)
	local args = getArgs(frame)
	local number  = args[1] or args.number or ''
	local inverse = args.inverse or 'false'
	
	if inverse == 'true' then
		return p.inverse(number)
	else
    	return p.thaiToArabicNum(number)
    end
end

function p.thaiToArabicNum(number)
	local character = splitChar(number)
	local output = ""
	local arabicnum = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }
	local thainum = { '๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙' }
	
	for i, char in pairs(character) do
		if indexOfTable(thainum, char) then
			output = output .. arabicnum[indexOfTable(thainum, char)]
		else
			output = output .. char
		end
	end
	
	return output
end

function p.inverse(number)
	local character = splitChar(number)
	local output = ""
	local arabicnum = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }
	local thainum = { '๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙' }
	
	for i, char in pairs(character) do
		if indexOfTable(arabicnum, char) then
			output = output .. thainum[indexOfTable(arabicnum, char)]
		else
			output = output .. char
		end
	end
	
	return output
end

return p