Skip to main content

/images/icons/xs_temp.svg For Each Loop

foreach ($list) {
  each as alias {
    // XanoScript statements go here
  }
}
ParameterPurposeExample
$listThe list to iterate through$users
$aliasThe variable to store the item currently being iterated throughuser
Place the functions that run as a part of your loop inside {} brackets after defining the alias.
foreach ($x1) {
  each as item {
    util.sleep {
      value = 1
    }
  }
}

/images/icons/xs_temp.svg For Loop

for (`$loops`) {
  each as index {
    // XanoScript statements go here
  }
}
ParameterPurposeExample
$loopsThe number of iterations in the loop10
$indexThe name of the index variableindex
Place the functions that run as a part of your loop inside {} brackets after defining the index variable.
for (`10`) {
  each as index {
    util.sleep {
      value = 1
    }
  }
}

/images/icons/xs_temp.svg While Loop

while (`conditions`) {
  each {
    // XanoScript statements go here
  }
}
ParameterPurposeExample
conditionsThe condition(s) that the loop will use to determine if it continues to runfalse == false && true == true
Place the functions that run as a part of your loop inside {} brackets after defining your conditions.
while (`true == true && true == true`) {
  each {
    util.sleep {
      value = 1
    }
  }
}

/images/icons/xs_temp.svg Break Out Of Loop

break
for (`10`) {
  each as index {
    conditional {
      if (`$index == 5`) {
        break
      }
    }
  }
}

/images/icons/xs_temp.svg Continue to Next Iteration

continue
for (`10`) {
  each as index {
    conditional {
      if (`$index == 5`) {
        continue
      }
    }
  }
}

Iterating Over an Array of Objects

You can access properties of each item in a foreach loop:
var $users {
  value = [
    {id: 1, name: "Alice"},
    {id: 2, name: "Bob"}
  ]
}

foreach ($users) {
  each as user {
    debug.log {
      value = user.name
    }
  }
}

Nested Loops

You can nest loops for multi-dimensional data:
var $matrix {
  value = [
    [1, 2],
    [3, 4]
  ]
}

foreach ($matrix) {
  each as row {
    foreach (row) {
      each as value {
        debug.log {
          value = value
        }
      }
    }
  }
}

When to Use For vs Foreach

  • Use for when you need a fixed number of iterations or an index variable.
  • Use foreach to iterate over each item in a list or array.

Notes on Break and Continue

The break and continue statements work in all loop types (for, foreach, and while). Use break to exit the loop early, and continue to skip to the next iteration.
I