I was developing my game and noticed that pointlessly repeating the same timer code over and over again is pointless when it wouldn’t be hard to write a class that makes it easy. For that reason, I threw together a quick and dirty class in about 3 minutes that works well. You give it an interval and it executes your callback or returns a boolean wether the time has passed. You can find the code here.
I’ve included a few examples in the main code, but there are other things I didn’t mention. For instance, you can change the interval on the fly by changing
timername.interval = # of seconds and change the callback by saying
timername.callback = callback function.
Let me know if you want more functions included like
reset() or something.
Don’t know is you saw this, but I too was bothered by the lack of simple, generic
timer functionality. Here’s mine that piggybacks off of tween:
@toadkick - I saw that while searching for a timer class. It’s quite creative, especially that you don’t have to call update, but it didn’t have the control I wanted and relied on another Lua library.
Fair enough. Maybe I’m missing something, but did you post yours somewhere? I’d love to check it out.
I assume that by another library you mean tween.lua? I thought that was kind of fair game since Codea includes it now.
Anyway yeah, I was mostly just interested in seeing how tween might be used for a timer. I also thought it might appeal to the camp that doesn’t like to put lots of update calls in their fraw function. It’s not really ideal, but it’s better than the ol’ “put a counter on the draw function” chestnut.
@toadkick - Sorry about that. The “here” in the sentence “You can find the code here.” has the link in it. I’ll make it bold.
Edit: And for the heck of it, italics and red.
Hi . In my windows library you will also find a WindowsTmers() class. It is standalone, can manage any number of timers, and is Speed optimized.
A much better attempt, that doesn’t use tween:
- Timer.lua no longer depends on Codea's class() function; it is now generic enough to be used independent of Codea.
- AutoTimer.elapsed changed to AutoTimer.update
- Use Timer/AutoTimer to have the callback pass no additional arguments to the timer callback.
- Use TimerDT/AutoTimerDT to have the timer pass an additional argument to your timer callback containing the elapsed time since the callback was last invoked (or since the timer was started)
- Use TimerE/AutoTimerE to have the timer pass an additional argument to your timer callback containing timer event data. Event data contains fields:
- eventdata.timer: timer calling callback
- eventdata.dt: elapsed time since callback last invoked (or since the timer was started)
- eventdata.n: number of times callback has been invoked since the timer was started