if语句卡在循环中,如何只运行一次?

时间:2014-11-20 10:23:29

标签: oop if-statement state imp squirrel

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

代码:

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 如果这会改变任何东西,但是我不认为这是

1 个答案:

答案 0 :(得分:2)

非常简单,真的。只需添加一个跟踪该语句是否已运行的变量。

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。

相关问题