Add local functions and closures
This commit is contained in:
parent
0dbf155da5
commit
e283991f90
2 changed files with 5 additions and 3 deletions
|
@ -153,7 +153,7 @@ class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Void visitFunctionStmt(Stmt.Function stmt) {
|
public Void visitFunctionStmt(Stmt.Function stmt) {
|
||||||
LoxFunction function = new LoxFunction(stmt);
|
LoxFunction function = new LoxFunction(stmt, environment);
|
||||||
environment.define(stmt.name.lexeme, function);
|
environment.define(stmt.name.lexeme, function);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,8 +4,10 @@ import java.util.List;
|
||||||
|
|
||||||
class LoxFunction implements LoxCallable {
|
class LoxFunction implements LoxCallable {
|
||||||
private final Stmt.Function declaration;
|
private final Stmt.Function declaration;
|
||||||
|
private final Environment closure;
|
||||||
|
|
||||||
LoxFunction(Stmt.Function declaration) {
|
LoxFunction(Stmt.Function declaration, Environment closure) {
|
||||||
|
this.closure = closure;
|
||||||
this.declaration = declaration;
|
this.declaration = declaration;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -16,7 +18,7 @@ class LoxFunction implements LoxCallable {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object call(Interpreter interpreter, List<Object> arguments) {
|
public Object call(Interpreter interpreter, List<Object> arguments) {
|
||||||
Environment environment = new Environment(interpreter.globals);
|
Environment environment = new Environment(closure);
|
||||||
|
|
||||||
for (int i = 0; i < declaration.params.size(); i++) {
|
for (int i = 0; i < declaration.params.size(); i++) {
|
||||||
environment.define(declaration.params.get(i).lexeme, arguments.get(i));
|
environment.define(declaration.params.get(i).lexeme, arguments.get(i));
|
||||||
|
|
Loading…
Reference in a new issue