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()})
点赞
用户1605727
用户1605727

你可以这样调用它:

function doSomething()
   print("这是一个示例函数")
end

function createPopup()
    local popup = display.newRect  ... 创建一些显示对象
    function popup:close()
        popup.isVisible = false
     end
    function popup:update(options)
        if options.action then
            function dg:touch(e)
                options.action() -- 这就是如何调用函数
            end
        end
    end
    popup:addEventListener("touch",popup)
    return popup
end

local mypopup = createPopup()

mypopup:update({action = doSomething})
2013-07-22 00:36:29
用户1682268
用户1682268

我对改变警告框文本信息有不同的方法,当你点击矩形时它将改变消息,第二次点击矩形。

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)
2013-07-22 00:47:43