diff --git a/README.md b/README.md index 12ec140..a136423 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,8 @@ Increases the internal timer in the clock by `dt`. `expired` will be true for one-time clocks whose time has passed, so their function has been invoked. -`local expired = clock:setTime(time)` -Changes the internal time manually. It never invokes `callback`. Returns whether the clock is expired. +`clock:reset([running])` +Changes the internal timer manually to `running`, or to 0 if nothing is specified. It never invokes `callback`. Examples @@ -42,8 +42,16 @@ Examples local c1 = cron.after(5, printMessage) local c2 = cron.after(5, print, 'Hello') + c1:update(2) -- will print nothing, the action is not done yet c1:update(5) -- will print 'Hello' once + c1:reset() -- reset the counter to 0 + + -- prints 'hey' 5 times and then prints 'hello' + while not c1:update(1) do + print('hey') + end + -- Create a periodical clock: local c3 = cron.every(10, printMessage) diff --git a/cron.lua b/cron.lua index bd3c3c7..6f3a8a5 100644 --- a/cron.lua +++ b/cron.lua @@ -86,6 +86,14 @@ local function updateEveryClock(self, dt) return false end +function Clock:reset(running) + running = running or 0 + checkPositiveInteger('running', running) + + self.running = running +end + + function cron.after(time, callback, ...) return newClock(time, callback, updateAfterClock, ...) end diff --git a/spec/cron_spec.lua b/spec/cron_spec.lua index 6b0e1c4..a698840 100644 --- a/spec/cron_spec.lua +++ b/spec/cron_spec.lua @@ -17,7 +17,7 @@ describe( 'cron', function() describe('clock', function() describe(':update', function() - it('throws an error if dt is a negative number', function() + it('throws an error if dt is not positive', function() local clock = cron.every(1, count) assert.error(function() clock:update() end) assert.error(function() clock:update(-1) end) @@ -25,6 +25,21 @@ describe( 'cron', function() end) end) + describe(':reset', function() + it('defaults to 0', function() + local clock = cron.every(1, count) + clock:update(1) + clock:reset(0) + assert.equal(clock.running, 0) + end) + it('throws an error if dt is not positive', function() + local clock = cron.every(1, count) + assert.error(function() clock:reset(-1) end) + assert.error(function() clock:reset('foo') end) + assert.not_error(function() clock:reset() end) + assert.not_error(function() clock:reset(1) end) + end) + end) end) @@ -68,6 +83,13 @@ describe( 'cron', function() end) + it('produces a clock that can be expired', function() + local c1 = cron.after(2, count) + assert.is_false(c1:update(1)) + assert.is_true(c1:update(1)) + assert.is_true(c1:update(1)) + end) + it('Passes on parameters to the callback', function() local c1 = cron.after(1, count, 2) c1:update(1)