From 48a80250bcb6104feba1ef16f6838cccccaa9626 Mon Sep 17 00:00:00 2001 From: Markus Freitag Date: Fri, 9 Dec 2022 18:52:31 +0100 Subject: [PATCH 1/2] evaluator: add break support for while loops --- evaluator/while.go | 5 +++++ tests/while.expected | 4 ++++ tests/while.rl | 18 +++++++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) 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() From 99a4fd7d4c67e0b5cbc241847f2b7e669007b6db Mon Sep 17 00:00:00 2001 From: Flipez Date: Sun, 18 Dec 2022 13:41:01 +0100 Subject: [PATCH 2/2] Update docs Signed-off-by: Flipez --- docs/docs/control_expressions/while.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) 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