conditionals
This commit is contained in:
23
vm/vm.go
23
vm/vm.go
@@ -87,12 +87,35 @@ func (vm *VM) Run() error {
|
||||
return err
|
||||
}
|
||||
|
||||
case code.OpJump:
|
||||
pos := int(code.ReadUint16(vm.instructions[ip+1:]))
|
||||
ip = pos - 1
|
||||
|
||||
case code.OpJumpNotTruthy:
|
||||
pos := int(code.ReadUint16(vm.instructions[ip+1:]))
|
||||
ip += 2
|
||||
|
||||
condition := vm.pop()
|
||||
if !isTruthy(condition) {
|
||||
ip = pos - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isTruthy(obj object.Object) bool {
|
||||
switch obj := obj.(type) {
|
||||
|
||||
case *object.Boolean:
|
||||
return obj.Value
|
||||
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (vm *VM) push(o object.Object) error {
|
||||
if vm.sp >= StackSize {
|
||||
return fmt.Errorf("stack overflow")
|
||||
|
||||
@@ -142,3 +142,17 @@ func TestBooleanExpressions(t *testing.T) {
|
||||
|
||||
runVmTests(t, tests)
|
||||
}
|
||||
|
||||
func TestConditionals(t *testing.T) {
|
||||
tests := []vmTestCase{
|
||||
{"if (true) { 10 }", 10},
|
||||
{"if (true) { 10 } else { 20 }", 10},
|
||||
{"if (false) { 10 } else { 20 } ", 20},
|
||||
{"if (1) { 10 }", 10},
|
||||
{"if (1 < 2) { 10 }", 10},
|
||||
{"if (1 < 2) { 10 } else { 20 }", 10},
|
||||
{"if (1 > 2) { 10 } else { 20 }", 20},
|
||||
}
|
||||
|
||||
runVmTests(t, tests)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user