我正在尝试取消Widget Candy按钮的onPress事件处理程序中的计时器。但是,即使我已将其定义为文件范围内的局部变量,timerId始终为nil。我是Lua开发的新手,所以我假设这个问题与变量范围有关,但是我很难找到一种方法来访问timer变量而不使它成为一个真正的全局变量(即声明它没有“local”关键字)。请参阅下面的代码段。
local countdownTimer = timer.performWithDelay(1000, handleCountdownTimer, countdown);
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 = function( 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
}
答案 0 :(得分:0)
尝试取消这样:
if(countdownTimer~=nil) -- Check whether timer is triggering or not
timer.cancel(countdownTimer)
end
答案 1 :(得分:0)
我发现您发布的代码没有任何问题:当onPress被调用时,您的countdownTimer应该是非零的。你不应该测试countdownTimer是否为零。在创建新的按钮之前打印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发现以上情况后仍无效):
我看不出有什么不对,所以我在我的电晕模拟器中对此进行了测试,并且没有任何问题,因此问题出在其他地方。这是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)