As the title says... Chat on...

User avatar
By equant
#56447 I am trying to use timers to blink some LEDs. However, I don't know how to pass an argument to the callback function to specify which pin to turn off. Here is some example code that doesn't work.

for pin in pairs(devices) do
myTimer = tmr.create()
tmr.alarm(myTimer, 5000, tmr.ALARM_SINGLE, function(myTimer, pin) print(pin) end)
end

Do I have to have a separately hardcoded timer for each pin, or can I do this in a way that lets me assign pins somewhere else, and dynamically create timers for them?
User avatar
By marcelstoer
#56978
equant wrote:I don't know how to pass an argument to the callback function


You need an intermediary function which takes that parameter and returns a closure:

Code: Select allfunction createCallback(which_pin)
  -- optional: local pin = which_pin
  return function()
    print(which_pin) -- or 'pin', see above
  end
end
for pin = 1, 10 do
  myTimer = tmr.create()
  tmr.alarm(myTimer, 5000, tmr.ALARM_SINGLE, createCallback(pin))
end


Reference: http://www.luafaq.org/#T1.28.1