diff options
Diffstat (limited to 'src/com/craftinginterpreters/lox/LoxLambda.java')
-rw-r--r-- | src/com/craftinginterpreters/lox/LoxLambda.java | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/com/craftinginterpreters/lox/LoxLambda.java b/src/com/craftinginterpreters/lox/LoxLambda.java new file mode 100644 index 0000000..8c87460 --- /dev/null +++ b/src/com/craftinginterpreters/lox/LoxLambda.java @@ -0,0 +1,40 @@ +package com.craftinginterpreters.lox; + +import java.util.List; + +class LoxLambda implements LoxCallable { + private final Expr.Lambda declaration; + private final Environment closure; + + LoxLambda(Expr.Lambda declaration, Environment closure) { + this.closure = closure; + this.declaration = declaration; + } + + @Override + public int arity() { + return declaration.params.size(); + } + + @Override + public Object call(Interpreter interpreter, List<Object> arguments) { + Environment environment = new Environment(closure); + + for (int i = 0; i < declaration.params.size(); i++) { + environment.define(declaration.params.get(i).lexeme, arguments.get(i)); + } + + try { + interpreter.executeBlock(declaration.body, environment); + } catch (Return returnValue) { + return returnValue.value; + } + + return null; + } + + @Override + public String toString() { + return "<fn anonymous>"; + } +} |