timer.performWithDelay()不返回变量重新分配表

时间:2017-07-22 01:23:29

标签: lua corona

目标

我有一个全局变量用于存储timer.performWithDelay返回的表。我的目标是,在场景中:show()函数用于取消定时器,并使用新的延迟重新创建。

问题

我在重新创建计时器时,在用于存储表的变量中获得nil返回值。

代码:

local timerVar

local function update()
    print("updating")
    print(timerVar)
    timer.cancel(timerVar)
    timerVar = timer.performWithDelay(delay, timerFunction, 0)
    print(timerVar)
end

function scene:create(event)
    timerVar = timer.performWithDelay(delay, timerFunction, 0)
end

function scene:show(event)
    if (phase == "will") then
        update()
        timer.resume(timerVar)
    end
end

function scene:hide(event)
    if (phase == "will") then
        timer.pause(timerVar)
    end
end

控制台输出:

updating
table: 095D9CA8
nil

这里发生了什么?

timer.cancel()是否完全删除了timerVar变量?
如果我不能保留计时器,我怎样才能解决这个问题,以便我可以将计时器表存储在相同的名称和相同的范围内,但重新出生?

2 个答案:

答案 0 :(得分:1)

我尝试重现你的问题,但得到了

updating
15:28:47.324  table: 0091F958
15:28:47.324  table: 0772C590
15:28:47.324  WARNING: timer.resume( timerId ) ignored because timerId was not paused.

我的代码:

main.lua

local composer = require( 'composer' ) 

composer.gotoScene( 'test' )

test.lua

local composer = require( "composer" )
local scene = composer.newScene()

local timerVar
local delay = 1000

local function timerFunction()

end   

local function update()
    print("updating")
    print(timerVar)
    timer.cancel(timerVar)
    timerVar = timer.performWithDelay(delay, timerFunction, 0)
    print(timerVar)
end


function scene:create( event )
   local sceneGroup = self.view
 timerVar = timer.performWithDelay(delay, timerFunction, 0)
end

function scene:show( event )
   local sceneGroup = self.view
   local phase = event.phase

   if ( phase == "will" ) then
       update()
        timer.resume(timerVar)
   elseif ( phase == "did" ) then

   end
end

function scene:hide( event )
   local sceneGroup = self.view
   local phase = event.phase

   if ( phase == "will" ) then
      timer.pause(timerVar)
   elseif ( phase == "did" ) then

   end
end

function scene:destroy( event )

   local sceneGroup = self.view
end

scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )

return scene

尝试安装最新稳定版的Corona。

答案 1 :(得分:0)

这在技术上并不是我的问题的直接答案,但它确实解决了我的问题,所以我将我的解决方法放在这里为未来的用户。只需更改定时器的延迟,我就可以完全避免取消定时器。这完成如下:

timerVar._delay = newDelay

请注意延迟变量之前的下划线,很容易错过。

这使我可以在不制作新计时器的情况下更新延迟。