|
|
@@ -12,10 +12,12 @@ import java.util.List;
|
|
|
public class LoxFunction implements LoxCallable {
|
|
|
private final Stmt.Function declaration;
|
|
|
private final Environment closure;
|
|
|
+ private final boolean isInitializer;
|
|
|
|
|
|
- public LoxFunction(Stmt.Function declaration, Environment closure) {
|
|
|
+ public LoxFunction(Stmt.Function declaration, Environment closure, boolean isInitializer) {
|
|
|
this.declaration = declaration;
|
|
|
this.closure = closure;
|
|
|
+ this.isInitializer = isInitializer;
|
|
|
}
|
|
|
|
|
|
@Override
|
|
|
@@ -32,8 +34,12 @@ public class LoxFunction implements LoxCallable {
|
|
|
try {
|
|
|
interpreter.executeBlock(declaration.body, environment);
|
|
|
} catch (Return returnVal) {
|
|
|
+ if (isInitializer) return closure.getAt(0, "this");
|
|
|
return returnVal.value;
|
|
|
}
|
|
|
+
|
|
|
+ if (isInitializer) return closure.getAt(0, "this");
|
|
|
+
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
@@ -41,17 +47,19 @@ public class LoxFunction implements LoxCallable {
|
|
|
Environment environment = new Environment(closure);
|
|
|
environment.define("this", instance);
|
|
|
|
|
|
- return new LoxFunction(declaration, environment);
|
|
|
+ return new LoxFunction(declaration, environment, isInitializer);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * <code>
|
|
|
- * fun add(a,b) {
|
|
|
- * print a + b;
|
|
|
- * }
|
|
|
- * <p>
|
|
|
+ *
|
|
|
+ *
|
|
|
+ * <pre>{@code
|
|
|
+ * fun add(a,b) {
|
|
|
+ * print a + b;
|
|
|
+ * }
|
|
|
+ *
|
|
|
* print add; // "<fn add>".
|
|
|
- * </code>
|
|
|
+ * }</pre>
|
|
|
*
|
|
|
* @return
|
|
|
*/
|