Corona SDK - 在 Widget Candy 按钮的 onPress 处理程序中取消定时器

我正在尝试在 Widget Candy 按钮的 onPress 事件处理程序中取消一个计时器。然而,timerId 总是为 nil,即使我已经在文件范围内定义了它作为一个局部变量。我是 Lua 开发的新手,所以我假设这个问题与变量作用域有关,但我很难找出一种在不将其变成真正的全局变量(即不使用“local”关键字声明)的情况下访问计时器变量的方法。请参见下面的代码片段。

点赞
用户1979583
用户1979583

尝试像这样取消:

if(countdownTimer~=nil)  -- 检查计时器是否正在触发
  timer.cancel(countdownTimer)
end
2014-03-10 05:08:01
用户869951
用户869951

我在你发布的代码中没有发现任何问题:当onPress被调用时,你的countdownTimer应该是非nil的。你不应该测试countdownTimer是否为nil。在你创建新按钮之前,在创建它后打印countdownTimer以确认它不为nil。还要搜索代码,找到所有引用变量的地方,并检查是否有任何地方将其设置为nil。

更新:

你可以尝试将函数移动并将其设置为本地函数:

local countdownTimer = timer.performWithDelay(1000, handleCountdownTimer, countdown);

local function cancelTimer( EventData )
    timer.cancel(countdownTimer); -- "countdownTimer" is always nil!!!
    local button = wcandy.GetHandle("MyButton1");
    if button:get("caption") == tostring(solution) then
        questionText:set("caption", "Correct!");
    else
        questionText:set("caption", "Wrong!");
    end
end

local answerButton1 = wcandy.NewButton
{
x       = "center",
y       = "55%",
width   = "75%",
name    = "MyButton1",
theme   = "theme_1",
border     = {"normal",6,1, .12,.12,0,.4,  .72,.72,.72,.6},
pressColor = {1,1,1,.25},
caption = "Touch me!",
textAlign   = "center",
fontSize    = "40",
onPress     = cancelTimer
}

更新2(@ husterk发现上述仍然无法工作后):

我没有发现任何错误,所以我在我的corona sim中对其进行了测试,没有问题,所以问题在其他地方。这里是完整的main.lua:

local widget = require('widget')

local function handleCountdownTimer(event)
    print('timed out; timer:', event.source)
end

local countdownTimer

local function cancelTimer( event )
    print('cancelling timout, timer:', countdownTimer)
    timer.cancel(countdownTimer)
end

local answerButton1 = widget.newButton
{
    onPress     = cancelTimer,
    width = 100,
    height = 100,
    label = 'hello',
    emboss = true
}

countdownTimer = timer.performWithDelay(10000, handleCountdownTimer)
print('timer started:', countdownTimer)
2014-03-10 16:21:51