Skip to content

Commit

Permalink
Merge pull request #168 from Flipez/while-break-support
Browse files Browse the repository at this point in the history
[evaluator/while]: Add support for `break`
  • Loading branch information
Flipez authored Dec 18, 2022
2 parents 4ce7753 + 99a4fd7 commit 44d0c79
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 1 deletion.
23 changes: 23 additions & 0 deletions docs/docs/control_expressions/while.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
5 changes: 5 additions & 0 deletions evaluator/while.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
4 changes: 4 additions & 0 deletions tests/while.expected
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,9 @@
2
0
1
3
4
5
6
0
ERROR: division by zero not allowed
18 changes: 17 additions & 1 deletion tests/while.rl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -25,4 +40,5 @@ def test_two()
end

test_one()
test_two()
test_two()
test_three()

2 comments on commit 44d0c79

@vercel
Copy link

@vercel vercel bot commented on 44d0c79 Dec 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on 44d0c79 Dec 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.