将函数执行一次放入“enterFrame”中。

我想让一个函数只在循环游戏中执行一次,

function loopGame(event)
       if c1 == true then
             ---执行一次功能
               comp()
        end
end

问题在于,我将这个loopGame放入了"enterFrame"的Runtime中,然后loopGame会在每一帧上执行,然后comp会执行超过100次。

我希望只执行一次comp。

谢谢。

点赞
用户1442917
用户1442917

你可以添加一个 upvalue 或全局变量来保持指示器,表明函数是否已经被调用过:

local executed = false -- 这将是 loopGame 函数的 upvalue
function loopGame(event)
       if c1 == true and not executed then
             ---执行一个函数
             comp()
             executed = true -- 设置指示器
        end
end

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

function loopGame(event)
       if c1 == true and comp then
             ---执行一个函数
             comp()
             comp = nil
        end
end
2014-01-22 23:36:22
用户1925928
用户1925928

如果你只需要运行一次,不要使用“enter frame”,试试这个:

function loopGame(event)
   if c1 == true then
         ---执行一个函数
           comp()
    end
end

Runtime:addEventListener( "goToLoopGame", loopGame )

并在想要开始loopGame函数的地方放置dispatch:

Runtime:dispatchEvent({ name = "goToLoopGame" })
2014-01-23 14:03:36
用户1076111
用户1076111

怎么样有两个函数,一个调用 comp,一个不调用:

function loopGameAfter(event)
       ... 其他内容 ...
end

function loopGameOnce(event)
       comp()
       ... 其他内容 ...
       Runtime:removeEventListener("enterFrame", loopGameOnce)
       Runtime:addEventListener("enterFrame", loopGameAfter)
end
2014-01-23 21:25:49
用户1979583
用户1979583

只需在调用 comp() 方法后将标志 c1 设为 false,如下所示:

function loopGame(event)
    if c1 == true then
        -- 执行一个函数
        comp()
        c1 = false     -- 只需添加此行并尝试
    end
end

继续编码.................. :)

2014-01-24 04:59:16