Corona SDK Pro Tip of the Day #34
Transition.to() for simple numbers

transition.to() and other similar functions are designed to work only on display objects. But what if you need to smoothly transition a simple number instead?

A recent tutorial from Corona Labs pushed me to share this method. The idea is to use a simple table instead of a display object and with help of a metatable track a variable being transitioned inside this table.

I'll take the code from that tutorial as a base and modify it to use a metatable and transition.to().

local scoreText = display.newText('', display.contentCenterX, 232, native.systemFontBold, 32)  
local score = 750800  
local duration = 4000

local function showScore(target, value, duration)  
    local mt = {}
    function mt.__index(t, k)
        if k == 'score' then return t._score end
    end
    function mt.__newindex(t, k, value)
        if k == 'score' then
            t._score = value
            target.text = string.format('%07d', value)
        end
    end

    local scoreTable = {_score = 0}
    setmetatable(scoreTable, mt)

    transition.to(scoreTable, {score = value, time = duration, transition = easing.outExpo})
end

showScore(scoreText, score, duration)  

This approach introduces metatables, but has less lines of code, independent of FPS, supports onComplete function and allows use of easings for the transition. easing.outExpo and easing.outQuad look nice for the score, slowing down at the end.

You can copy paste this code into your main.lua and it will work.

How does it work? Well, we use a dummy table scoreTable with the only purpose is to hold the metatable mt, which is the real worker. scoreTable also holds a hidden field scoreTable._score that holds value for the "virtual" scoreTable.score field.

When you read or write to scoreTable.score a respective metamethod is called: __index() or __newindex() respectively. It only works if such field does not exist in the table.

__index() returns value of _score and __newindex() writes value to _score and updates the text object target. This happens every frame.

Indie Game Developer