首页 文章

Lua:为回调函数添加参数

提问于
浏览
1

短篇小说:如何将参数传递给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 . 我'd assume that'可能是数字变量的初始化值 .

1 回答

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

相关问题