glox/callable.go

37 lines
553 B
Go
Raw Normal View History

2024-10-09 19:57:52 +03:00
package main
type Callable struct {
arity int
call func(*Interpreter, ...any) any
}
2024-10-09 23:36:18 +03:00
func newCallable(f *FunStmt) *Callable {
return &Callable{
arity: len(f.args),
2024-10-11 17:01:12 +03:00
call: func(i *Interpreter, args ...any) (ret any) {
defer func() {
if err := recover(); err != nil {
re, ok := err.(Return)
if !ok {
panic(err)
}
ret = re.val
}
}()
2024-10-09 23:36:18 +03:00
env := newEnvironment(i.globals)
for idx, arg := range f.args {
2024-10-11 17:01:12 +03:00
env.define(arg.lexeme, args[idx])
2024-10-09 23:36:18 +03:00
}
i.executeBlock(f.body, env)
return nil
},
}
}