执行一次“enterFrame”功能

时间:2014-01-22 22:03:39

标签: lua corona

我想让一个函数执行一次进入循环游戏,

function loopGame(event)
       if c1 == true then
             ---Execute one function
               comp()
        end
end

问题是我将这个loopGame放入运行时使用“enterFrame”,并且loopGame是exec for frame,然后comp执行超过100次。

我想要一次只执行一次。

由于

4 个答案:

答案 0 :(得分:3)

如果函数已被调用,您可以添加一个upvalue或一个全局值来保持指示符:

local executed = false -- this will be an upvalue for loopGame function
function loopGame(event)
       if c1 == true and not executed then
             ---Execute one function
             comp()
             executed = true -- set the indicator
        end
end

另一个选择是使用函数本身作为指标;如果它没有在其他地方使用(例如,它只进行一次初始化),那么你可以在完成后将函数设置为nil(并节省一些内存):

function loopGame(event)
       if c1 == true and comp then
             ---Execute one function
             comp()
             comp = nil
        end
end

答案 1 :(得分:3)

如果你需要它运行一次,不要使用“输入框架”试试这个:

function loopGame(event)
   if c1 == true then
         ---Execute one function
           comp()
    end
end

Runtime:addEventListener( "goToLoopGame", loopGame )

将调度发送到loopGame函数的任何位置:

Runtime:dispatchEvent({ name = "goToLoopGame" })

答案 2 :(得分:3)

在调用c1=false方法后,只需制作标记comp(),如下:

function loopGame(event)
    if c1 == true then
      --Execute one function
        comp()
        c1 = false     -- Just add this line and try
     end
end

保持编码..................:)

答案 3 :(得分:2)

如果有两个函数,一个调用comp,另一个调用comp:

function loopGameAfter(event)
       ... other stuff ...
end

function loopGameOnce(event)
       comp()
       ... other stuff ...
       Runtime:removeEventListener("enterFrame", loopGameOnce)
       Runtime:addEventListener("enterFrame", loopGameAfter)
end
相关问题