Module:Sandbox/Mdowdell/Coins Explained

--

--
-- Implements {{Coins}} and {{Rusty coins}}
--

local p = {}

--
-- {{Coins}} access point
--
function p.amount(frame)
    local args = frame:getParent.args
    -- for {{coins|111}} or {{coins|amount=111}}
    local a = args[1] or args.Amount or args.amount
    return p._amount(a)
end

--
-- {{Rusty coins}} access point
--
function p.rusty(frame)
    local args = frame:getParent.args
    local a = args[1] or args.Amount or args.amount
    return p._amount(a, true)
end

--
-- @param a {number} Number to output with coins image
-- @param rusty {boolean} If true, outputs rusty coins image. Defauts to false
-- @return {string}
--
function p._amount (a, rusty)
    -- convert used globals to locals where possible to improve performance
    local tostring = tostring
    local tonumber = tonumber
    local mw = mw

    local a = tostring(a) or '0'
    local color = 'green'
    local img = '1'

    -- strip commas from input
    -- @example {{GEPrice|Foo}} -> '1,000'
    a = a:gsub(',', '')

    -- cache tonumber(a) to improve performance a bit
    num_a = tonumber(a)

    -- dirty way of replicating #expr
    -- should be able to be replaced by backporting
    -- <https://git.wikimedia.org/commit/mediawiki%2Fextensions%2FParserFunctions/ea7bc2880a5e6e71d5b6c904e5299cdde30817bd>
    --
    -- only do this if required so as not to impact performance too much
    if num_a == nil then
        a = mw.getCurrentFrame:preprocess('{{#expr:' .. a .. '}}')
        num_a = tonumber(a)

        if num_a == nil then
            num_a = 0
        end
    end

    -- round to 2 d.p.
    a = math.floor(num_a * 100 + 0.5) / 100

    -- set the color
    -- blue for positive, red for negative, green for zero
    -- default 'green' set above
    if a > 0 then
        -- blue
        color = '#014cc0'
    elseif a < 0 then
        -- red
        color = '#c02614'
    end

    -- set the coins image
    -- default '1' set above
    local num = math.abs(a)
    local amounts = { 1000, 250, 100, 25, 5, 4, 3, 2 }
    local i, j

    for i = 1, 8 do
        j = amounts[i]

        if num >= j then
            img = tostring(j)
            break
        end
    end

    if not rusty then
        img = '[[File:Coins ' .. img .. '.png|link=Coins]]'
    else
        img = '[[File:Rusty coins ' .. img .. '.png|link=Rusty coins]]'
    end

    -- format number with commas
    a = mw.language.getContentLanguage:formatNum(a)

    -- return '<span class="coins/rusty-coins ' .. 'coins-XXXX ' .. 'coins-pos/neg">' .. a .. '</span>'

    return '<span class="coins-templ" style="white-space:nowrap; color:' ..
        color .. '">' .. img .. '&nbsp;' .. a .. '</span>'
end

return p