How to pass a variable to uloop.timer lua timer binding from ubus callback

I want to write a service in lua which uses uloop lua binding.

Description:
In the a ubus callback i want to start a timer with a callback function.
My Problem is that i get a variable from the ubus call which the timer function should use.

Question:
How will i do this?

Code example:

#!/usr/bin/env lua

require "ubus"
require "uloop"

uloop.init()

local conn = ubus.connect()
if not conn then
	error("Failed to connect to ubus")
end

local timer
function t()
	print("1000 ms timer run");
	timer:set(1000)
end

local my_method = {
	test = {
		hello = {
			function(req, msg)
				print("Call to function 'hello'")
                                timer = uloop.timer(t)
                                timer:set(1000)
				conn:reply(req, {message="foo"});
			end, {id = ubus.INT32, msg = ubus.STRING }
		}
	}
}

uloop.run()

For example:
I want to use the id in the timer callback function.

I'd say you can solve that by using a closure.

local my_method = {
	test = {
		hello = {
			function(req, msg)
				print("Call to function 'hello'")
				local id = msg.id
                                timer = uloop.timer(function() t(id) end)
                                timer:set(1000)
				conn:reply(req, {message="foo"});
			end, {id = ubus.INT32, msg = ubus.STRING }
		}
	}
}
1 Like

Thanks works as expected

1 Like