Lua 脚本按键事件重复不停止

简单的问题却不容易解决:

我有一个循环和一些变量,在 OnEvent(event,arg)函数中这些变量会改变。

但是在循环中它却不能检测到改变,例如:

local cancel_action = false

function OnEvent(event, arg)
  if (event == "MOUSE_BUTTON_PRESSED" and arg == 2) then
    cancel_action = not cancel_action
    OutputLogMessage("DETECT  cancel_action :")
    OutputLogMessage(tostring(cancel_action))
  end

  if (event == "MOUSE_BUTTON_PRESSED" and arg == 3) then
    test()
  end
end

function test()
  count_ = 0
  repeat
     count_ = count_ + 1
     OutputLogMessage("cancel_action ?")
     OutputLogMessage(tostring(cancel_action))
     if ( cancel_action ) then
       OutputLogMessage("do something and stop")
       cancel_action = not cancel_action
       break
     else
        OutputLogMessage("do something else and loop again")
     end
  until count_ > 10
end

在这里,cancel_action 的更改可以在 OnEvent 函数中检测到并正常工作,但在 test 函数中却永远无法检测到。

所以,总结一下,我想使用保持状态的变量,但在我的测试函数中,状态没有正确更新。

我做错了什么?是否可以在循环中检测到变量的更改?事件似乎只有在循环结束后触发。

原文链接 https://stackoverflow.com/questions/69676163

点赞
stackoverflow用户2858170
stackoverflow用户2858170

你在循环中没有更新 cancel_action,而当你的代码忙于运行循环时,不会处理更多的事件。那么 cancel_action 应该如何更改它的值呢?

使用 IsMouseButtonPressed(2) 来终止你的循环。

2021-10-22 12:12:02