Functions 10
This commit is contained in:
parent
7f4946f1e9
commit
e9e3c992cb
4 changed files with 20 additions and 2 deletions
|
|
@ -106,7 +106,7 @@ class Interpreter : Stmt.Visitor!void, Expr.Visitor!TValue {
|
|||
evaluate(stmt.expression);
|
||||
}
|
||||
void visit(Stmt.Function stmt){
|
||||
LoxFunction func = new LoxFunction(stmt);
|
||||
LoxFunction func = new LoxFunction(stmt, environment);
|
||||
environment.define(stmt.name.lexeme, TValue.cal(func));
|
||||
}
|
||||
void visit(Stmt.If stmt){
|
||||
|
|
|
|||
|
|
@ -10,11 +10,15 @@ import jlox.util;
|
|||
|
||||
class LoxFunction : LoxCallable{
|
||||
private Stmt.Function declaration;
|
||||
private Environment closure;
|
||||
mixin defaultCtor;
|
||||
invariant{
|
||||
assert(declaration && closure);
|
||||
}
|
||||
|
||||
int arity() => declaration.params.length.to!int;
|
||||
TValue call(Interpreter interpreter, TValue[] arguments){
|
||||
Environment environment = new Environment(interpreter.globals);
|
||||
Environment environment = new Environment(closure);
|
||||
foreach(i; 0 .. declaration.params.length)
|
||||
environment.define(declaration.params[i].lexeme, arguments[i]);
|
||||
try{
|
||||
|
|
|
|||
|
|
@ -17,5 +17,6 @@ void main(){
|
|||
}
|
||||
assert([ "./lox", "test/fib21.lox" ].execute.output == fib(6765));
|
||||
assert([ "./lox", "test/fib10.lox" ].execute.output == fib(34));
|
||||
assert([ "./lox", "test/closure.lox" ].execute.output == "1\n2\n");
|
||||
}
|
||||
|
||||
|
|
|
|||
13
test/closure.lox
Normal file
13
test/closure.lox
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
|
||||
fun makeCounter(){
|
||||
var i = 0;
|
||||
fun counter(){
|
||||
return i = i + 1;
|
||||
}
|
||||
return counter;
|
||||
}
|
||||
|
||||
var counter = makeCounter();
|
||||
print counter(); // "1".
|
||||
print counter(); // "2".
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue