XScript Manual · Chapter 3

title: "Control Flow — if / for / while" chapter: 3 images:

  • xscript-control-flow.png

Control Flow

XScript supports three control-flow constructs: if, for, and while. Opening braces always go on the next line (project style rule).

if

if (IO["I_Start"] == ON)
{
    Log("start pressed");
}
else if (IO["I_Reset"] == ON)
{
    Log("reset pressed");
}
else
{
    // idle
}

Real-world pattern

// Combined sensor + flag + server-response condition
if (SYS.IsRunning && SS.UseServerRetryCount == ON
    && Common::IsMeasureUnit(ErrorUnitIndex)
    && retries < maxRetries)
{
    ret = Micom::Send(ErrorUnitIndex, "send_error_reply", "reply=retry", true);
}

for

XScript's for uses comma-separated arguments: for(var, start, end) or for(var, start, end, step).

// i = 0..count-1 (ascending)
for (i, 0, count - 1)
{
    moduleName = $"Module{i+1}";
    totalUnitCount += JSON.GetIntValue(jsonName, $"modules[{i}].category.unitCount");
}
 
// Reverse iteration (step = -1)
for (i, count - 1, 0, -1)
{
    DisplayList.Add(Data::ReorderNumbers[i]);
}

while

Repeats while the condition is true. Common in equipment wait loops.

int startTick = SYS.TickCount;
 
while (UnitData::IsSending[unitIndex - 1] == OFF)
{
    Sleep(100);
    if (SYS.GetElasped(startTick) > 2000)
    {
        LogError($"{unitName} IsSending ON Failed");
        ShowError(EB_Reset, 1210, $"{unitName}:IsSending ON Failed");
        return false;
    }
}

Caution : while(true) infinite loops are forbidden — always include a timeout and an exit condition. For simple waits, prefer IO[name].Wait(true, ms) or MOTOR[name].Wait(ms).

Flow-control keywords

KeywordDescription
returnEnd current function/step. return false signals failure.
breakExit current loop
continueSkip current iteration
goto "STEP_name"Jump to another step in the sequence
for (i, 0, SS.UnitCount - 1)
{
    if (UnitData::UnitOrderNumber[i] == "")
    {
        continue;  // skip empty units
    }
 
    if (SendUnitOrderItemStatus(i, status) == false)
    {
        result = false;
        break;     // stop on failure
    }
}

Tips

  • Opening brace always on the next line.
  • Return immediately with return false after ShowError().
  • Split long conditions across lines; use a temp bool if it helps readability.
  • Keep nesting depth ≤ 2; refactor into a function otherwise.