It's a good start. I think there's some room for improvement.
Avoid global variables
Use the
local keyword to create local variables and functions, and return a table with the things you want to export. This way everything stays encapsulated; your timer module doesn't interfere with other code and other code doesn't interfere with it.
Use meaningful identifiers
For the most part it's fine, but some identifiers don't convey their purpose well. For example, consider renaming
start to
elapsed and
times to
timer.
Use care when modifying arrays during iteration
Code: Select all
local x = { 1, 2, 3, 4, 5 }
for k, v in pairs(x) do
if v == 3 then
table.remove(x, k)
end
print(v)
end
-- prints 1, 2, 3, 5 ... where'd 4 go?
table.remove moves things around in the array. When you do this while iterating, you may end up skipping some items. Reverse iterate if you want to use
table.remove, or ditch the numeric indices and just set things to
nil (since you're using
pairs anyway).
Be efficient
Code: Select all
for name, a in pairs(activeTimers) do
table.remove(activeTimers, name)
end
The code above is very inefficient; for every item in the table, the item is removed and every other item is repositioned, until there are no items left. Just write
activeTimers = {} instead.
Give me a handle to my timer
Suppose I created two different timers that share the same function (
func) but execute at different times, and with different arguments (
arg). Now suppose I want to "delete" one timer but not the other. I can't do it, because
deleteTimer wants me to pass in
func, and both timers share
func. Consider having
timer return the table that was inserted into
activeTimers, and have
deleteTimer accept that table (the actual timer) rather than the callback function that was attached to it.