Random functions/classes #4: Simple timer class


--# Main
-- Timer Class

-- Use this function to perform your initial setup
function setup()
    timer = Timer(5,function() done() end,WIDTH/2,HEIGHT/2)
    started=true
end

function draw()
    background(0)

    timer:draw()
end

function touched(t)
    if t.state==ENDED then timer:reset() end
end

--# Timer
Timer = class()

function Timer:init(start,action,x,y)
    self.starttime = start
    self.time = start
    self.action = action
    self.pos = vec2(x,y)
end

function Timer:draw()
    if started then self.time = self.time - DeltaTime end
    self.minutes = math.floor(self.time/60)
    self.seconds = math.floor(self.time-self.minutes*60)

    if math.floor(self.time)==0 then
        started=false
        if pcall(self.action) then
            self.action()
        else
            text("Error: expected a function",WIDTH/2,200)
        end
    end
    
    fill(84, 224, 64, 255)
    font("HelveticaNeue")
    fontSize(40)
    text(string.format("%02d",self.minutes)..":"..string.format("%02d",self.seconds),self.pos.x,self.pos.y)
end

function Timer:reset()
    self.time = self.starttime
    started = true
end

function done()
    background(255)
    text("Times Up!",WIDTH/2,100)
end

You can use this in your project if you want

Nice timer class. But you should try using DeltaTime instead of 1 / 60, if you use DeltaTime it’ll be accurate regardless of the FPS or lag. Also, you can use pcall() to run self.action without having to check if self.action exists and to prevent crashes.

@SkyTheCoder how do you use pcall()? I tried doing a forum search but they didn’t really explain it

@Doge - google “lua pcall”

its also easy to use tweens for timers:

function delay(time, callback, loop)
    tween(time, {}, {}, nil, function()
        if loop ~= nil then
            if type(loop) == "number" then loop = loop - 1 end
            if loop == true or loop >= 1 then delay(time, callback, loop) end
        end
        callback()
    end)
end

call:

function setup()
    delay(1, function() print("after one second") end)
end

I updated the code above and added pcall() and DeltaTime