Lua: 为回调函数添加参数

Lua: Add parameter for callback function

小故事:如何将参数传递给 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。我假设这可能是数字变量的初始化值。

首先,您的代码根本不会 运行...照原样,它会抛出一个

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()