timer.performWithDelay() 函数重新分配变量时没有返回表格

目标

我创建了一个全局变量来存储timer.performWithDelay返回的表格。我的目标是在scene: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变量?

如果我不能保留计时器,我该如何解决此问题,以便我可以将计时器表格存储在相同的名称和范围下,但新生?

点赞
用户7026995
用户7026995

我尝试复现您的问题,但是得到了以下的结果:

更新中
15:28:47.324  表格: 0091F958
15:28:47.324  表格: 0772C590
15:28:47.324  警告: 计时器.resume( 计时器ID ) 被忽略,因为计时器ID未被暂停。

我的代码:

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("更新中")
    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。

2017-07-22 13:33:08
用户5679974
用户5679974

这并不是一个技术上直接回答我的问题的答案,但它确实解决了我的问题,因此我将我的解决方法放在这里以供未来的用户参考。我能够通过简单地更改定时器的延迟时间来避免完全取消定时器。这可以通过如下方式完成:

timerVar._delay = newDelay

注意变量之前的下划线,很容易被忽略。

这使我能够更新延迟时间而无需创建一个新的定时器。

2017-08-02 16:36:03