Pardon the mess, Play My Code is in beta!

READY TO PLAY?
CLICK TO LOG IN!

sign up - lost password

Loops

Where is the For loop?

Quby doesn't support a standard for or for-each loop. Instead you use call methods on the object your iterating on and define a 'block' that handles the loop contents. For example to iterate from 0 to n you can do...

// the Number class has a 'times' method for iteration
10.times() do |i|
    // do things here
end

// .. and 'upTo', 'downTo', 'to', and you can build your own!
20.upTo( 100 ) do |i|
    // do stuff with i here
end

For iterating over the elements of an array, the Array class supports the 'each' method.

names = [ 'Brian', 'John', 'Graham', 'George' ]

names.each() do |name|
    // do stuff with val here
end

While Loop

Proper while loops can be built using the 'while' keyword, and end using 'end'.

while a > b
    b = b + 1
end

A condition is given after the 'while', which is evaluated before each iteration. It will run, repeatedly, until the condition becomes false.

Until Loop

The until loop is very similar to the while loop. It is defined with 'until' instead of 'while', but will run whilst the condition is false.

until player.isDead()
    player.damage()
end

When the condition becomes true, the loop will end. For example the same could be written as:

while not player.isDead()
    player.damage()
end

Loop-While and Loop-Until

The while loop and until loops evaluate their condition before the loop. There is also an inverse type of loop, which evaluates the condition after the loop.

loop
    a = a - 1
end while a > b

loop
    a = a + 1
end until a > b

They use the 'loop' keyword to start, and then 'end while' or 'end until', followed by a condition, to finish.

As the condition is evaluated after the loop, these will always loop at least once.

See Also