Loops

Astra has one loop keyword — repeat — that handles both count-based and condition-based loops. Clean, simple, and powerful.

Count Loop

Loop from 1 to N using repeat i to N:

loop.astra
repeat i to 5 write i ; \\ Output: 1 2 3 4 5
💡 Note: The iterator starts at 1 by default and increments by 1 each step.

Custom Range & Step

Specify start, end, and step using repeat i to (start, end, step):

Custom Start

repeat i to (5, 10) write i ; \\ Output: 5 6 7 8 9 10

Custom Step

\\ Even numbers repeat i to (2, 10, 2) write i ; \\ Output: 2 4 6 8 10

Reverse Loop

\\ Count down repeat i to (10, 1, -1) write i ; \\ Output: 10 9 8 7 6 5 4 3 2 1

While-style Loop

Use repeat (condition) for condition-based loops:

while.astra
x = 1 repeat (x <= 5) write x x++ ; \\ Output: 1 2 3 4 5

Real-world example

total = 0 n = user:Enter a number: repeat (n > 0) total += n n-- ; write "Sum: " + total

Nested Loops

Loops can be nested inside each other:

nested.astra
\\ Multiplication table repeat i to 3 repeat j to 3 write i * j ; ; \\ Output: 1 2 3 2 4 6 3 6 9

break

Exit a loop early with break:

break.astra
repeat i to 10 if i == 5 break ; write i ; \\ Output: 1 2 3 4

break in while loop

x = 0 repeat (true == true) x++ if x == 5 break ; ; write x \\ 5

continue

Skip the current iteration and move to the next with continue:

continue.astra
\\ Skip odd numbers — print only even repeat i to 10 if i % 2 != 0 continue ; write i ; \\ Output: 2 4 6 8 10
📌 Note: break and continue work in both count loops and while-style loops.

Loop with Chains

Use len() to loop over a chain:

chain-loop.astra
a:n = 10, 20, 30, 40, 50 \\ Print all elements repeat i to len(a:n) write a[i] ; \\ Double all elements repeat i to len(a:n) a[i] = a[i] * 2 ; write a:n \\ 20 40 60 80 100

Named chain loop

students:n(name, score) = ("Alice", 90), ("Bob", 85), ("Charlie", 95) repeat i to len(students:n) write students[i]:name + " — " + students[i]:score ; \\ Output: \\ Alice — 90 \\ Bob — 85 \\ Charlie — 95

Sum with loop

numbers:n = 10, 20, 30, 40, 50 total = 0 repeat i to len(numbers:n) total += numbers[i] ; write "Total: " + total \\ Total: 150