In my last post, I talked about using a button action to access text input from a text box. This could then be added to a table or saved to a database, or both in my case. For this post, I will discuss how to build a timer for an app.
Other people have already solved this problem, so I found an awesome tutorial (https://coronalabs.com/blog/2015/04/28/tutorial-implementing-a-countdown-timer/) from corona labs.
This tutorial was easy to follow, the code was clear to understand, it runs quickly, and it works. Everything you want in a tutorial. Here’s my final snippet of code for a functional timer that sits in the top left corner of the screen. I put this code in the “DID” section of the scene creation management within composer so that the timer wouldn’t start until the scene was loaded and on screen. The mui functions come from the Material-UI library which I am using to help me design my user experience (http://www.anedix.com/docs/mui/).
elseif ( phase == “did” ) then
local secondsLeft = 3 * 60
local clockText = display.newText(
clockText:setFillColor( 1,1,1,1 )
sceneGroup:insert( clockText )
local function updateTime()
secondsLeft = secondsLeft – 1
if secondsLeft <= 0 then
–print(“Time is up!”) –run function that ends the level/scene
–for x,y in pairs(responsesTable) do
— time is tracked in seconds. We need to convert it to minutes and seconds
local minutes = math.floor( secondsLeft / 60 )
local seconds = secondsLeft % 60
— make it a string using string format.
local timeDisplay = string.format( “%02d:%02d”, minutes, seconds )
clockText.text = timeDisplay
— run the timer
local countDownTimer = timer.performWithDelay( 1000, updateTime, secondsLeft )
Next post I’ll discuss input/output, pulling text from a file, and using the system resource directory.
EDIT: I changed if seconds == 0 to if seconds <= 0 just in case a problem makes the program skip 0.