1

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

高级我有创建弹出窗口的代码。当我用新文本更新弹出窗口时,我还想更新用户单击弹出窗口时发生的操作。例如,当我第一次更新弹出窗口时,我可能会将 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()})
4

2 回答 2

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})
于 2013-07-22T00:36:29.290 回答
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)
于 2013-07-22T00:47:43.180 回答