Version 3 (modified by hopscc, 14 years ago) |
---|
While Statement
The while statement is used to repeatedly execute code while a condition is true.
Grammar
[post] while <expression> <statements>
Without the post, the expression is first evaluated and while true, the statements are executed.
If the expression evaluates false the first time, the statements will not execute.
With post, the condition is evaluated 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 should be 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