Skip to content

Commit 0d903d4

Browse files
committed
fix type casting after binary operation
1 parent ed2bbe3 commit 0d903d4

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

evaluator.go

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package runevm
22

33
import (
44
"fmt"
5+
"math"
56
"os"
67
"strconv"
78
"strings"
@@ -342,14 +343,10 @@ func applyBinaryOp(op string, a, b interface{}, exp *Expr) interface{} {
342343
return parseNumber(v, exp).(float64)
343344
case int:
344345
return float64(v)
345-
case int32:
346-
return float64(v)
347-
case int64:
348-
return float64(v)
349346
case float32:
350347
return float64(v)
351348
case float64:
352-
return v
349+
return float64(v)
353350
default:
354351
Error(exp, "Expected number but got %T", x)
355352
return 0
@@ -378,15 +375,22 @@ func applyBinaryOp(op string, a, b interface{}, exp *Expr) interface{} {
378375
}
379376
return false
380377
}
378+
roundIfInt := func(value float64) interface{} {
379+
if math.Abs(value-math.Round(value)) < 1e-9 {
380+
return int(value)
381+
}
382+
return value
383+
}
384+
381385
switch op {
382386
case "+":
383-
return num(a) + num(b)
387+
return roundIfInt(num(a) + num(b))
384388
case "-":
385-
return num(a) - num(b)
389+
return roundIfInt(num(a) - num(b))
386390
case "*":
387-
return num(a) * num(b)
391+
return roundIfInt(num(a) * num(b))
388392
case "/":
389-
return num(a) / div(b)
393+
return roundIfInt(num(a) / div(b))
390394
case "%":
391395
return int(num(a)) % int(num(b))
392396
case "&&":

example/test.rune

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
1-
foo = "bar"
1+
2+
a = 10
3+
b = 10.0000
4+
c = a + b
5+
println(typeof(c))
26
exit()
37

8+
foo = "bar"
9+
410
testFun = fun() {
511
foo = "bar"
612
println(foo)

0 commit comments

Comments
 (0)