【问题标题】:Execute function one time into "enterFrame"在“enterFrame”中执行一次函数
【发布时间】:2014-01-22 22:03:39
【问题描述】:

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

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

问题是我把这个loopGame用“enterFrame”放到了Runtime中,loopGame是exec for frame,然后comp被执行了100多次。

我想要一次只执行一次。

谢谢

【问题讨论】:

  • 如果这是一个多线程环境,你可能需要一些同步块。

标签: lua coronasdk


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    function loopGame(event)
       if c1 == true then
             ---Execute one function
               comp()
        end
    end
    
    Runtime:addEventListener( "goToLoopGame", loopGame )
    

    并将调度放置在您希望它启动 loopGame 函数的任何位置:

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2015-07-04
          • 1970-01-01
          • 1970-01-01
          • 2013-05-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-05
          相关资源
          最近更新 更多