functions with arguments
Some checks failed
Build / build (push) Failing after 22s
Test / build (push) Failing after 22s

This commit is contained in:
Chuck Smith
2024-03-12 15:53:35 -04:00
parent ec9a586f7f
commit 1d2c7f0a51
6 changed files with 203 additions and 13 deletions

View File

@@ -203,13 +203,13 @@ func (vm *VM) Run() error {
}
case code.OpCall:
fn, ok := vm.stack[vm.sp-1].(*object.CompiledFunction)
if !ok {
return fmt.Errorf("calling non-function")
numArgs := code.ReadUint8(ins[ip+1:])
vm.currentFrame().ip += 1
err := vm.callFunction(int(numArgs))
if err != nil {
return err
}
frame := NewFrame(fn, vm.sp)
vm.pushFrame(frame)
vm.sp = frame.basePointer + fn.NumLocals
case code.OpReturnValue:
returnValue := vm.pop()
@@ -465,6 +465,23 @@ func (vm *VM) executeMinusOperator() error {
return vm.push(&object.Integer{Value: -value})
}
func (vm *VM) callFunction(numArgs int) error {
fn, ok := vm.stack[vm.sp-1-numArgs].(*object.CompiledFunction)
if !ok {
return fmt.Errorf("calling non-function")
}
if numArgs != fn.NumParameters {
return fmt.Errorf("wrong number of arguments: want=%d, got=%d", fn.NumParameters, numArgs)
}
frame := NewFrame(fn, vm.sp-numArgs)
vm.pushFrame(frame)
vm.sp = frame.basePointer + fn.NumLocals
return nil
}
func nativeBoolToBooleanObject(input bool) *object.Boolean {
if input {
return True