2017-01-06 184 views
0

小故事:如何將參數傳遞給Lua中的回調函數?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.如我期望的那樣。我會假設這可能是數字變量的初始值。

+0

'buttonPinPressed'如何設置爲1? – hjpotter92

+0

對不起,這只是張貼錯誤。我改變了代碼。 var是buttonPin,而不是buttonPinPressed。問題依然存在。 對於格式化,感到抱歉,當時你並行地改變它。 – Jens

+1

變化'函數(buttonPin)notifyButtonPressed(buttonPin)end'到'()函數notifyButtonPressed(buttonPin)end' – hjpotter92

回答

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... 

爲了您的回調工作完美,您必須爲每個按鈕傳遞不同的函數,而不是嘗試傳遞arg功能...請試試這個:

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