Lua:为回调函数添加参数

时间:2017-01-06 11:23:43

标签: lua esp8266 nodemcu

短篇小说:如何将参数传递给Lua中的回调函数?

长篇故事:

我在使用NodeMCU固件的ESP8266上工作。基本上我打算构建一个破折号按钮,每个节点只有多个按钮。我这样做是因为GPIO引脚的中断可能性。

然而,如何将参数传递给回调函数似乎没有得到很好的记录。在我的情况下,我想知道中断来自哪个引脚。这就是我提出的。它的工作原理除了引脚的值,它似乎在触发时重置为初始化值1。

  -- Have an area to hold all pins to query (in testing only one)

  buttonPins = { 5 }
  direction="up"

  armAllButtons()

  function armAllButtons()
    for i,v in ipairs(buttonPins)
    do
        armButton(v)
    end
  end


  function armButton(buttonPin)
    print("Arming pin "..buttonPin.." for button presses.")

    gpio.mode(buttonPin,gpio.INT,gpio.FLOAT)
    gpio.trig(buttonPin, direction, function (buttonPin) notifyButtonPressed(buttonPin) end)

    print("Waiting for button press on "..buttonPin.."...")
  end

  function notifyButtonPressed(buttonPin)
    print("Button at pin "..buttonPin.." pressed.")

    --rearm the pins for interrupts
    armButton(buttonPin)
  end

然而,在notifyButtonPressed()函数中,buttonPin的值在按下时始终为1,而不是我预期的5。我假设这可能是数字变量的初始化值。

1 个答案:

答案 0 :(得分:1)

首先,你的代码根本不运行......因为它会抛出一个

input:6: attempt to call a nil value (global 'armAllButtons')

我重新安排你的代码片段之后:

  buttonPins = { 5 }
  direction="up"

  function armButton(buttonPin)
    print("Arming pin "..buttonPin.." for button presses.")

    gpio.mode(buttonPin,gpio.INT,gpio.FLOAT)
    gpio.trig(buttonPin, direction, function (buttonPin) --notifyButtonPressed(buttonPin) end)

    print("Waiting for button press on "..buttonPin.."...")
  end

  function notifyButtonPressed(buttonPin)
    print("Button at pin "..buttonPin.." pressed.")

    --rearm the pins for interrupts
    armButton(buttonPin)
  end

  function armAllButtons()
    for i,v in ipairs(buttonPins)
    do
        armButton(v)
    end
  end

armAllButtons()

输出:

Arming pin 5 for button presses.
Waiting for button press on 5...

为了完美地回调你的工作,你必须为每个按钮传递一个不同的函数,而不是试图将参数传递给函数...试试这个:

  buttonPins = { 5 }
  direction="up"

  function armButton(buttonPin)
    print("Arming pin "..buttonPin.." for button presses.")

    gpio.mode(buttonPin,gpio.INT,gpio.FLOAT)
    gpio.trig(
      buttonPin, 
      direction, 
      function ()
        notifyButtonPressed(buttonPin) 
      end
    ) -- this should create a function for each button, and each function shall pass a different argument to notifyButtonPressed

    print("Waiting for button press on "..buttonPin.."...")
  end

  function notifyButtonPressed(buttonPin)
    print("Button at pin "..buttonPin.." pressed.")

    --rearm the pins for interrupts
    armButton(buttonPin)
  end

  function armAllButtons()
    for i,v in ipairs(buttonPins)
    do
        armButton(v)
    end
  end

armAllButtons()