Skip to content
Dennis Rönn edited this page Oct 4, 2022 · 1 revision

Dern currently does not support loops, but you can use Functions with recursion to get a similar effect.
In the future when Dern supports Lambdas you could use function callbacks as an effective replacement for standard loops when using recursion.

Examples (Recursion)

Example taken from Functions#other-examples.

func printNumLoop($number: n) -> $void {
    if (n < 0) {
        return;
    }

    printNumLoop(n - 1);
    print(n);
}

printNumLoop(9);

Bi-Directional Loop

If you want a bi-directional loop, you may use this loop, which has start (inclusive) and end (exclusive) as a parameters.
Of course, you'd adapt to use these in a way more suitable to your use case

func loop($number: index, $number: end) -> $void {
    if (index == end) {
        return;
    }

    var step = 1;
    if (index > end) {
        step = -step;
    }

    print(index);
    loop(index + step, end);
}

Using this code, running loop(2, 6) and loop(7, 3) would give these 2 outputs:
1)

2
3
4
5

2)

7
6
5
4

Clone this wiki locally