ข้ามไปเนื้อหา

มอดูล:ThaiToArabicNum

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

เอกสารการใช้งานสำหรับมอดูลนี้อาจสร้างขึ้นที่ มอดูล:ThaiToArabicNum/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?
        Kinda. It does not work properly with comparison by character (original method in sandbox), 
        but it works with using string.gsub (and probably the less expensive method here). ||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

function p.main(frame)
    local args = getArgs(frame)
    local number  = args[1] or args.number or ''
    
    return p.thaiToArabicNum(number)
end

function p.thaiToArabicNum(number)
    local arabicnum = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }
    local thainum = { '๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙' }
    
    for i, v in ipairs(thainum) do
        number = string.gsub(number, thainum[i], arabicnum[i])
    end
    
    return number
end

return p