2013-07-22 49 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) 
相关问题