foreach Loop

The foreach loop iterates over the elements of an array, the characters of a string, or the values of an object.

foreach variable in expression do
    # body
end

The do keyword is required. The block is closed with end.

Iterating Over Arrays

foreach item in Data.items do
    item.processed = true
end

Iterating Over Strings

When the source is a string, each iteration yields a single-character string:

foreach ch in "hello" do
    # ch is "h", "e", "l", "l", "o"
end

Iterating Over Objects

When the source is an object, foreach iterates over the object’s values:

foreach val in Data.scores do
    total += val
end

To iterate over an object’s keys, use Keys():

foreach key in Keys(Data.scores) do
    var value = Data.scores[key]
end

Loop Variable Scoping

The iteration variable is scoped to the loop body and does not exist outside the loop.

Collection Modification

Modifying the collection being iterated causes a runtime error. Use a separate collection for additions:

# INCORRECT - runtime error
foreach item in Data.items do
    Data.items = Append(Data.items, item)
end

# CORRECT - collect into a separate array
var additions = []
foreach item in Data.items do
    if item.shouldDuplicate then
        additions = Append(additions, item)
    end
end
foreach addition in additions do
    Data.items = Append(Data.items, addition)
end

Back to top

Copyright © Mesch Systems 2025-2026. All rights reserved.