[SOLVED] How to stop this timer?

Hi!
I’m doing a timed laser that will swith on and off.
The thing is I don’t know how to stop this timer.
Here’s the code :

[lua]laser.timer = function(isActive)
local stop
local tOff = timerOff
local tOn = timerOn
local clock
if isActive == true then
local on
local off
function on(e)
timer.cancel(e.source)
e.source = nil
laser.switchOn()
clock = timer.performWithDelay( tOn, off )
end
function off(e)
timer.cancel(e.source)
e.source = nil
laser.switchOff()
clock = timer.performWithDelay( tOff, on )
end
clock = timer.performWithDelay( 1, on )
else
timer.cancel( clock )
clock = nil
end
end[/lua]

I’m sending a boolean value to active the switching. But when sending FALSE, console says “Whoops, that timer doesn’t exist!”

Thanks [import]uid: 25327 topic_id: 18262 reply_id: 318262[/import]

Remember that local variables only exist inside the instance of whatever is using them. If you call the function separate times (once to turn things on, once to turn things off), those two calls are two separate instances. Which means when you try to cancel the timer, the “clock” variable is nil since it hasn’t been set yet in the instance being created by the second function call.

There are two quick fixes you can make:

  1. Remove “local clock”. So that clock becomes a module-wide variable.
  2. Move “local clock” out of and above the function so it is no longer local to it. [import]uid: 36054 topic_id: 18262 reply_id: 69937[/import]

Hi Blasterv!

Yeah, accessing this timer is my main problem. This function is attached to the laser while in the constructor (which is a module ) so I can’t access it from the main game module.

What if I declare the timer as laser.clock ?
I might be able to access it from the main game module like this :
timer.cancel( laser.clock )

Will try that now.

Thanks [import]uid: 25327 topic_id: 18262 reply_id: 69941[/import]

I believe what you’re planning will work. [import]uid: 36054 topic_id: 18262 reply_id: 69943[/import]

Yeah!
That’s worked perfectly.
Here’s the updated code.
I added a stopTimer function to get rid of the timer easily.

[lua]laser.startTimer = function()
local tOff = timerOff
local tOn = timerOn
local on
local off
function on(e)
timer.cancel(e.source)
e.source = nil
laser.switchOn()
laser.clock = timer.performWithDelay( tOn, off )
end
function off(e)
timer.cancel(e.source)
e.source = nil
laser.switchOff()
laser.clock = timer.performWithDelay( tOff, on )
end
laser.clock = timer.performWithDelay( 1, on )
end
laser.stopTimer = function()
timer.cancel(laser.clock)
laser.clock = nil
end [import]uid: 25327 topic_id: 18262 reply_id: 69947[/import]