diff --git a/docs/docs/control_expressions/while.md b/docs/docs/control_expressions/while.md index 4f79aad..480c60a 100644 --- a/docs/docs/control_expressions/while.md +++ b/docs/docs/control_expressions/while.md @@ -23,3 +23,26 @@ end 3 => nil ``` + +It is possible to use `next` or `break` inside a while loop. + +```js +i = 0 +while (i < 10) + if (i < 3) + i = i + 1 + next + end + puts(i) + if (i == 6) + break + end + i = i + 1 +end + +// which prints +3 +4 +5 +6 +``` \ No newline at end of file diff --git a/evaluator/while.go b/evaluator/while.go index c069e83..58ce50c 100644 --- a/evaluator/while.go +++ b/evaluator/while.go @@ -14,6 +14,11 @@ func evalWhile(w *ast.While, env *object.Environment) object.Object { if rt != nil && (rt.Type() == object.RETURN_VALUE_OBJ || rt.Type() == object.ERROR_OBJ) { return rt } + + if rt != nil && rt.Type() == object.BREAK_VALUE_OBJ { + return rt.(*object.BreakValue).Value + } + v = Eval(w.Condition, env) } diff --git a/tests/while.expected b/tests/while.expected index a9d4dd4..3674bf4 100644 --- a/tests/while.expected +++ b/tests/while.expected @@ -3,5 +3,9 @@ 2 0 1 +3 +4 +5 +6 0 ERROR: division by zero not allowed diff --git a/tests/while.rl b/tests/while.rl index 76e56bc..a2964e1 100644 --- a/tests/while.rl +++ b/tests/while.rl @@ -17,6 +17,21 @@ def test_one() end def test_two() + i = 0 + while (i < 10) + if (i < 3) + i = i + 1 + next + end + puts(i) + if (i == 6) + break + end + i = i + 1 + end +end + +def test_three() a = 0 while (a != 3) puts(a) @@ -25,4 +40,5 @@ def test_two() end test_one() -test_two() \ No newline at end of file +test_two() +test_three()