| 1 | The '''while''' statement is used to repeatedly execute code while a condition is true. |
| 2 | === Grammar === |
| 3 | {{{ |
| 4 | while-statement = |
| 5 | [post] while <expression> |
| 6 | <statements> |
| 7 | }}} |
| 8 | |
| 9 | 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. |
| 10 | |
| 11 | 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). |
| 12 | |
| 13 | {{{ |
| 14 | #!cobra |
| 15 | # Example 1 |
| 16 | while obj.someCondition |
| 17 | obj.process |
| 18 | |
| 19 | # Example 2 |
| 20 | while node |
| 21 | print node |
| 22 | node = node.next |
| 23 | |
| 24 | # Example 3 |
| 25 | while node |
| 26 | if not node.isActive |
| 27 | print 'skipping inactive node: [node]' |
| 28 | continue |
| 29 | print node |
| 30 | node.process |
| 31 | node = node.next |
| 32 | |
| 33 | # Example 4 |
| 34 | while true |
| 35 | input = Console.readLine |
| 36 | if input is nil or input.trim.toLower == 'exit' |
| 37 | break |
| 38 | .processInput(input) |
| 39 | |
| 40 | # Example 5 |
| 41 | post while line and line.trim == '' |
| 42 | line = stream.readLine |
| 43 | }}} |