【问题标题】:if statement stuck in loop, how to run it only once?if语句卡在循环中,如何只运行一次?
【发布时间】:2015-01-18 04:03:01
【问题描述】:

我正在创建一个系统,该系统将在每次温度传感器超出限制时发送文本。我只需要发送一次此文本,但它会一直发送。

代码:

if(temp > (userTemp + 5.00))
    {
        ledState2=1;
        device.send("led2", ledState2);

        local smsState = 0; //State, if sms has been sent yet or not

        if(smsState==0)
        {
            smsState=1;
            //This is where the sms script will be put
            server.log("SMS should send: " + smsState);         
        }
    }

输出:

2014-11-20 10:12:58 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:08 UTC+0   [Device]    22.3245
2014-11-20 10:13:08 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:09 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:18 UTC+0   [Device]    22.2814
2014-11-20 10:13:18 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:19 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:28 UTC+0   [Device]    22.3245
2014-11-20 10:13:28 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:29 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:38 UTC+0   [Device]    22.2814
2014-11-20 10:13:39 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:39 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:48 UTC+0   [Device]    22.3245
2014-11-20 10:13:49 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:49 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:13:58 UTC+0   [Device]    22.2814
2014-11-20 10:13:59 UTC+0   [Agent] SMS should send: 1
2014-11-20 10:13:59 UTC+0   [Device]    Set RED LED: 1
2014-11-20 10:14:08 UTC+0   [Device]    22.3029
2014-11-20 10:14:09 UTC+0   [Agent] SMS should send: 1

我不明白为什么要继续发送 server.log 当我输入应该只运行一次的 smsState if 语句时,因为我将 smsState 更改为 1 这是一个电动小鬼,如果这会改变任何东西,但我不认为它会改变

【问题讨论】:

  • 不确定该语言中的关键字local 是什么意思,但似乎每次您输入此块时都会完成local smsState = 0; //State, if sms has been sent yet or not,并且您的smsState 变量正在重置。您应该考虑将其设置为全局变量,或者使用 OOP 方法创建一个 SMSer 对象来执行发送,该对象在被静默忽略 msgs(或类似的东西)的存根调用后被替换。
  • 非常感谢,我以为我已经尝试过了,但现在工作得很好

标签: oop if-statement state imp squirrel


【解决方案1】:

真的很简单。只需添加一个变量来跟踪语句是否已运行。

local didSend = 0;

if(temp > (userTemp + 5.00) && !didSend)
{
    didSend = 1;

    ledState2=1;
    device.send("led2", ledState2);

    local smsState = 0; //State, if sms has been sent yet or not

    if(smsState==0)
    {
        smsState=1;
        //This is where the sms script will be put
        server.log("SMS should send: " + smsState);         
    }
}

现在 if 语句将不会再次运行,直到您再次将 didSend 更改回 0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多