Language Reference: Loops

For and while loops, running code iteratively (multiple times)

Loops allow programs to run code iteratively (multiple times). Pointless has two traditional looping constructs: for loops and while loops.


For Loops

The basic form of a for loop has the syntax

for variable in sequence do
  ...block
end

in which

A for loop iterates over the values in a data-structure sequence. Those values will be:

For each value in sequence, the for loop will store the value in variable and evaluate the code in ...block. In the example below, the code total += n runs 5 times, once for each value in numbers, with n taking on the value of each number in numbers in order.

numbers = [1, 2, 3, 4, 5]
total = 0

for n in numbers do
  total += n
end

total
15

for loops are statements, meaning they don't produce values directly. Instead, they are used to run code containing side effects (like updating a variable).

Note that the map $ and filter ? operators are often used instead of for loops.


Tandem For Loops

states = ["Afghanistan", "Albania", "Algeria", "Andorra", "Angola"]

for index, state in states do
  print("$index $state")
end
0 Afghanistan
1 Albania
2 Algeria
3 Andorra
4 Angola

Anonymous For Loops

fibonacci = [0, 1]

-- Add the next 5 Fibonacci numbers to the list
for 10 do
  fibonacci |= push(fibonacci[-1] + fibonacci[-2])
end

fibonacci
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

While Loops

n = 7
seq = [n]

while n > 1 do
  n = if Math.isEven(n) then n / 2 else n * 3 + 1 end
  seq |= push(n)
end

seq
[7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]