I have a long-standing recurring problem when programming with add_timer() / remove_timer() using these API functions.
The problem is that I can’t find a way to pass a variable through the timer add_timer().
For example, if I want to execute a function without delay with a variable in the function I can do this:
--the function 1 without timer
local function my_func(variable)
print(variable)
if renoise.tool():has_timer(my_func) then
renoise.tool():remove_timer(my_func)
end
end
--bang!
my_func(20)
--the result is that it will print 20 immediately.
On the other hand, if I use add:timer(), how do I pass said variable “20”?
--the function 2 with timer
local function my_timer(variable)
if not renoise.tool():has_timer(my_func) then
renoise.tool():add_timer(my_func,1000) -- variable???
end
end
--bang!
my_timer(20)
--The result will not print the variable "20" after 1 second. It will probably print "nil".
Does anyone know how to pass this variable?
It is no use defining a local outside the function, because that local could change. During that second it should not be possible for the variable to change in any way!
The related documentation from API (Renoise.ScriptingTool.API.lua):
--[[
Register a timer function or table with a function and context (a method)
that periodically gets called by the app_idle_observable for your tool.
Modal dialogs will avoid that timers are called. To create a one-shot timer,
simply call remove_timer at the end of your timer function. Timer_interval_in_ms
must be > 0. The exact interval your function is called will vary
a bit, depending on workload; e.g. when enough CPU time is available the
rounding error will be around +/- 5 ms.
]]
-- Returns true when the given function or method was registered as a timer.
renoise.tool():has_timer(function or {object, function} or {function, object})
-> [boolean]
-- Add a new timer as described above.
renoise.tool():add_timer(function or {object, function} or {function, object},
timer_interval_in_ms)
-- Remove a previously registered timer.
renoise.tool():remove_timer(timer_func)
The objective is to be able to call the same function my_func(variable) several times in quick succession but only the last call is executed.
For example, if I call the function my_func(variable) 10 times in a row, through the other function with a timer, the timer should avoid executing the first 9 calls, executing the 10th call, obviously passing the variable through the timer.