Neon
← Back to Conditional blocksNext: Defining functions →

Loops

Loops allow repeating code multiple times.


1. while Loops

Repeats a block of code while a condition is true.

Syntax

while (condition) do
    # Code to repeat
end

Examples

# Count from 1 to 5
i = 1
while (i <= 5) do
    print(i)
    i += 1
end

# Infinite loop (use with caution!)
while (True) do
    print("This will never stop!")
end

# User input loop
guess = 0
secret = 42
while (guess != secret) do
    guess = int(input("Guess the number: "))
    if (guess < secret) then
        print("Too low!")
    elif (guess > secret) then
        print("Too high!")
    end
end
print("Correct!")

2. for Loops

Repeats a block of code for a range of integer values.

Syntax

# Full form
for (variant, start, end, step) do
    # Code to repeat
end

# Simplified forms
for (variant, start, end) do    # step = 1
    ...
end

for (variant, end) do           # start = 0, step = 1
    ...
end

Examples

# Print numbers 0 to 4
for (i, 0, 5) do
    print(i)
end

# Print even numbers from 2 to 10 (step = 2)
for (i, 2, 11, 2) do
    print(i)
end

# Countdown from 5 to 1
for (i, 5, 0, -1) do
    print(i)
end

# Simplified (0 to 4)
for (i, 5) do
    print(i)
end

Notes on for Loops


3. foreach Loops

Iterates over each element in a list or string.

Syntax

foreach (element, iterable) do
    # Code to repeat for each element
end

Examples

# Iterate over a list
fruits = ["apple", "banana", "cherry"]
foreach (fruit, fruits) do
    print(fruit)
end

# Iterate over a string (each character)
foreach (char, "Neon") do
    print(char)
end

# Sum all numbers in a list
numbers = [1, 2, 3, 4, 5]
sum = 0
foreach (num, numbers) do
    sum += num
end
print(sum)  # → 15

Notes on foreach


Loop Control Statements

break

Exits the innermost loop immediately.

Example:

while (True) do
  if (x > 10) then
    break
  end
end

continue

Jumps to the beginning of the next iteration of the loop.

Example:

for (i, 10) do
  if (i % 2 == 0) then
    continue
  end
  print(i) # Only prints odd numbers
end

Result:

1
3
5
7
9

pass

Does nothing (placeholder).

Example:

if (x > 0) then
  pass
else
  print("Negative")
end
← Back to Conditional blocksNext: Defining functions →