2013-07-22 50 views
1

我試圖在另一個函數中將函數作爲參數傳遞。Lua/Corona - 如何傳遞函數作爲參數,然後調用該函數

高級別我有創建一個彈出窗口的代碼。當我用新文本更新彈出窗口時,我還想更新用戶單擊彈出窗口時發生的操作。例如,我第一次更新彈出窗口時,我可能會將該操作更改爲用新文本再次顯示彈出窗口。當用戶點擊第二

下面是一些示例代碼來說明這個概念

function doSomething() 
    print("this is a sample function") 
end 

function createPopup() 
    local popup = display.newRect ... create some display object 
    function popup:close() 
     popup.isVisible = false 
    end 
    function popup:update(options) 
     if options.action then 
      function dg:touch(e) 

       -- do the action which is passed as options.action 

      end 
     end 
    end 
    popup:addEventListener("touch",popup) 
    return popup 
end 

local mypopup = createPopup() 

mypopup:update({action = doSomething()}) 

回答

6

你可以這樣調用

function doSomething() 
    print("this is a sample function") 
end 

function createPopup() 
    local popup = display.newRect ... create some display object 
    function popup:close() 
     popup.isVisible = false 
    end 
    function popup:update(options) 
     if options.action then 
      function dg:touch(e) 
       options.action() -- This is how you call the function 
      end 
     end 
    end 
    popup:addEventListener("touch",popup) 
    return popup 
end 

local mypopup = createPopup() 

mypopup:update({action = doSomething}) 
+1

不應該在表構造函數中調用'doSomething';只需將該字段設置爲函數值本身:'{action = doSomething}'。 –

+0

我沒有看到那個 – NaviRamyle

+0

太棒了,我能夠得到這個工作! –

0

我有不同的方法上改變了文本消息警告看到這個代碼,當你點擊矩形時它會在第二次點擊它時改變消息

local Message = "My Message" 
local Title = "My Title" 
local nextFlag = false 


local function onTap() 
local alert = native.showAlert(Title, Message, { "OK", "Cancel" }, onComplete) 
end 


function onComplete(event) 

    if nextFlag == true then 
     if "clicked" == event.action then 
      local i = event.index 
      Message = "My Message" 
      Title = "My Title" 
      if 1 == i then 
      nextFlag = false 
      -- you can add an event here 
     elseif 2 == i then 
      -- if click cancel do nothing 
     end 
     end 

    else 
     if "clicked" == event.action then 
     local i = event.index 
     Message = "Change message" 
      Title = "Change Title" 
     if 1 == i then 
      nextFlag = true 
      -- you can add an event here 
      elseif 2 == i then 
      -- if click cancel do nothing 
     end 
     end 
    end 

end 

local rectangle = display.newRect(120,200, 100,100) 
rectangle:addEventListener("tap", onTap) 
相關問題