Wiki
Version 2 (modified by todd.a, 13 years ago)

--

While Statement

The while statement is used to repeatedly execute code while a condition is true.

Grammar

while-statement =
    [post] while <expression>
        <statements>

Without the post, the expression is checked first and while true, the statements are repeatedly executed. If the expression is false the first time, the statements will not execute. With the post, the condition is checked after the statements execute, so the statements will execute at least once.

Inside the statements, a break statement will exit the loop and a continue statement will skip the remaining statements and evaluate the expression again. In either case, an if statement is used to control when the loop is broken or continued (otherwise it would be pointless to have further statements in the loop).

# Example 1
while obj.someCondition
    obj.process

# Example 2
while node
    print node
    node = node.next

# Example 3
while node
    if not node.isActive
        print 'skipping inactive node: [node]'
        continue
    print node
    node.process
    node = node.next

# Example 4
while true
    input = Console.readLine
    if input is nil or input.trim.toLower == 'exit'
        break
    .processInput(input)

# Example 5
post while line and line.trim == ''
    line = stream.readLine