2021-03-12 10:23:54 +00:00
|
|
|
--[[
|
|
|
|
basic timer class
|
|
|
|
|
|
|
|
can check for expiry and register a callback to be called on progress and on finish
|
|
|
|
|
|
|
|
if you find yourself using lots of these for pushing stuff into the future,
|
|
|
|
look into async.lua and see if it might be a better fit!
|
|
|
|
]]
|
|
|
|
|
|
|
|
local path = (...):gsub("timer", "")
|
|
|
|
local class = require(path .. "class")
|
2021-07-15 06:09:08 +00:00
|
|
|
local timer = class({
|
|
|
|
name = "timer",
|
|
|
|
})
|
2021-03-12 10:23:54 +00:00
|
|
|
|
|
|
|
--create a timer, with optional callbacks
|
2021-07-18 01:30:22 +00:00
|
|
|
--callbacks receive as arguments:
|
2021-03-12 10:23:54 +00:00
|
|
|
-- the current progress as a number from 0 to 1, so can be used for lerps
|
|
|
|
-- the timer object, so can be reset if needed
|
|
|
|
function timer:new(time, on_progress, on_finish)
|
2021-07-15 06:09:08 +00:00
|
|
|
self.time = 0
|
|
|
|
self.timer = 0
|
|
|
|
self.on_progress = on_progress
|
|
|
|
self.on_finish = on_finish
|
|
|
|
self:reset(time)
|
2021-03-12 10:23:54 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
--update this timer, calling the relevant callback if it exists
|
|
|
|
function timer:update(dt)
|
|
|
|
if not self:expired() then
|
|
|
|
self.timer = self.timer + dt
|
|
|
|
|
|
|
|
--get the relevant callback
|
|
|
|
local cb = self:expired()
|
|
|
|
and self.on_finish
|
|
|
|
or self.on_progress
|
|
|
|
|
|
|
|
if cb then
|
|
|
|
cb(self:progress(), self)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
--check if the timer has expired
|
|
|
|
function timer:expired()
|
|
|
|
return self.timer >= self.time
|
|
|
|
end
|
|
|
|
|
|
|
|
--get the timer's progress from 0 to 1
|
|
|
|
function timer:progress()
|
|
|
|
return math.min(self.timer / self.time, 1)
|
|
|
|
end
|
|
|
|
|
2021-03-12 10:44:09 +00:00
|
|
|
--reset the timer; optionally change the time
|
2021-03-12 10:23:54 +00:00
|
|
|
--will resume calling the same callbacks, so can be used for intervals
|
2021-03-12 10:44:09 +00:00
|
|
|
function timer:reset(time)
|
2021-03-12 10:23:54 +00:00
|
|
|
self.timer = 0
|
2021-03-12 10:44:09 +00:00
|
|
|
self.time = math.max(time or self.time, 1e-6) --negative time not allowed
|
|
|
|
return self
|
2021-03-12 10:23:54 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
return timer
|