You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
At the end of Chapter 12 dealing with classes in jlox we make the init method always return this, and then in the next section we prevent the use of returning any other value from init. However the check preventing return statements only applies to statements with a value, and doesn’t prevent “plain” return statements.
This means it is possible to return nil from init, which I don”t think is the intention.
class Foo {
init() {
return;
}
}
var f = Foo();
print f.init(); // -> nil
Removing the return, the above code prints Foo instance.
One fix is to add a check when catching the return value in LoxFunction#call, only returning the value if the function isn’t an initializer and letting it fall through if it is:
try {
interpreter.executeBlock(declaration.body, environment);
} catch (ReturnreturnValue) {
if (!isInitializer) { // <- add this check herereturnreturnValue.value;
}
}
if (isInitializer) {
returnclosure.getAt(0, "this");
}
Another possibility could be to prevent allreturn statements in initializers, but I don’t think that’s the right choice.
The text was updated successfully, but these errors were encountered:
At the end of Chapter 12 dealing with classes in jlox we make the
init
method always returnthis
, and then in the next section we prevent the use of returning any other value frominit
. However the check preventingreturn
statements only applies to statements with a value, and doesn’t prevent “plain”return
statements.This means it is possible to return
nil
frominit
, which I don”t think is the intention.Removing the
return
, the above code printsFoo instance
.One fix is to add a check when catching the return value in
LoxFunction#call
, only returning the value if the function isn’t an initializer and letting it fall through if it is:Another possibility could be to prevent all
return
statements in initializers, but I don’t think that’s the right choice.The text was updated successfully, but these errors were encountered: