简体   繁体   English

Lua在计时器上交替一个值

[英]Lua alternating a value on a timer

I am in quite a pickle right now. 我现在很泡菜。

I have a switch that I need to be able to turn on and off every second but I don't really know how I would do that because it needs to be applied on the same bit/function If currently have a bit that functions as an on/off for a function, the problem is that I need a way for that function to turn itself on and off every 1 second. 我有一个开关,我必须能够每秒打开和关闭一次,但我真的不知道该怎么做,因为它需要应用于相同的位/功能。打开/关闭某个功能,问题是我需要一种方法使该功能每1秒打开和关闭一次。 I have tried this so far but it is not working for me. 到目前为止,我已经尝试过了,但是对我来说不起作用。 Could anyone try and solve this issue for me please? 谁能为我解决这个问题?

{$lua}
if not syntaxcheck then

  local On = 1
  local Off = 0
  local Switch = OnOffController

  local function OnOff()
    if Switch = Off then
      Switch = On
    if Switch = On then
      Switch = Off
    end
    end
  end

    OnOff()
    if(Second == nil) then
      Second = createTimer(getMainForm())
      Second.Interval = 1000
      Second.OnTimer = function(timer)
        OnOff()
      end
    end
  Second.setEnabled(true)
  end

While there could be more wrong, there's definitely an issue with the OnOff() function: 尽管可能存在更多错误,但OnOff()函数肯定存在问题:

local function OnOff()
    if Switch = Off then
      Switch = On
    if Switch = On then
      Switch = Off
    end
    end
end

The two nested if statements are not going to do what you want. 这两个嵌套的if语句不会执行您想要的操作。 First off, you're using the assignment operator = rather than the equals operator == . 首先,您使用赋值运算符=而不是等于运算符== Even if that were correct though the logic has a problem. 即使这是正确的,尽管逻辑有问题。 If Switch is On going into the first if the flow will bypass both. 如果“ Switch为“ On ,则进入第一个流程( if流程将绕过两者)。 If Switch is Off going into the first if it'll first get changed to On and then immediately hit the second condition and get changed back to Off . 如果Switch处于Off ,则首先if其更改为On ,然后立即达到第二个条件,然后将其更改为Off

You probably want something more like: 您可能想要更多类似的东西:

local function OnOff()
    if Switch == Off then
        Switch = On
    else
        Switch = Off
    end
end

You don't need the second comparison at all assuming Switch can only be true or false. 假设Switch只能为true或false,您根本不需要第二个比较。

Other bits of advice I'd give would be to use a boolean type for the Switch variable as that makes it explicit that it can only have two values. 我会给出的其他建议是对Switch变量使用布尔类型,因为它明确表明它只能有两个值。 You'd probably also want to change its name to something like SwitchedOn or the like to make it obvious what true and false would mean in its context. 您可能还希望将其名称更改为SwitchedOn之类的名称,以使其在上下文中明显地表示对与错。 Likewise a name like ToggleSwitch may make it a bit more obvious what the function presently called OnOff is intended to do. 同样,类似ToggleSwitch的名称可能会使它现在ToggleSwitchOnOff的功能意图更加明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM