Lua / Corona - 如何将函数作为参数传递然后调用该函数

时间:2013-07-22 00:28:57

标签: function lua corona

我正在尝试将函数作为参数传递给另一个函数。

高级别我有代码创建一个弹出窗口。当我用新文本更新弹出窗口时,我还想更新用户单击弹出窗口时发生的操作。例如,我第一次更新弹出窗口时,我可能会将Action更改为再次使用新文本显示弹出窗口。当用户点击第二个

以下是一些示例代码来说明概念

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

2 个答案:

答案 0 :(得分: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 :(得分: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)