Big List of Defold Pro Tips!

Dynamic instance of watch - helper function

If you need to start a timer in a dynamically changing environment and you need to ensure, that you didn’t started any or overwrite the current ticking or cancel some countdown you can make use of this little wrapper module I wrote:

local WD = {}

local id = 0

function WD.create(delay, cb, repeat_flag)
	local instance = {
		delay = delay,
		cb = cb,
		repeat_flag = repeat_flag or false
	}
	id = id + 1
	instance.id = id
	instance.stop = function()
		if instance.handle and instance.handle ~= timer.INVALID_TIMER_HANDLE then
			timer.cancel(instance.handle)
			instance.handle = nil
			print("Stopped watch ", instance.id)
		else
			print("Stopping watch FAILED", instance.id, instance.handle)
		end
	end
	instance.start = function()
		instance.stop()
		instance.handle = timer.delay(instance.delay, instance.repeat_flag, instance.cb)
		assert(instance.handle ~= timer.INVALID_TIMER_HANDLE, "Starting watch FAILED - id:"..instance.id)
	end

	print("Created Watch with delay", delay)
	return instance
end

return WD

Example:

local watch = require "path.to.watch"

local zoom_to_normal = watch.create(2, function() msg.post(HERO_CAM, m.ZOOM, {zoom = m.NORMAL}) end)

-- when input released try to start a timer, which will change the zoom after 2 sec:
zoom_to_normal.start()

-- when input is pressed cancel the current countdown (if any):
zoom_to_normal.stop()

I’m using it to because even if I trigger some countdown in one state, the player could quickly change it (move further, so you’re leaving idle state), so I needed to ensure the callback won’t be called when I’m in different state - thus the .stop() method is useful.

5 Likes