@@ -72,9 +72,14 @@ static void initCompiler(BytecodeGen* gen, Compiler* compiler, CompFunctionType
7272 local -> name = "" ; // Internal usage
7373}
7474
75- static ObjFunction * endCompiler (BytecodeGen * gen ) {
75+ static ObjFunction * endCompiler (BytecodeGen * gen , bool isInit ) {
7676 // Emit return
77- writeChunk (gen -> chunk , OP_NIL , 0 );
77+ if (isInit ) {
78+ writeChunk (gen -> chunk , OP_GET_LOCAL , 0 );
79+ writeChunk (gen -> chunk , 0 , 0 );
80+ } else {
81+ writeChunk (gen -> chunk , OP_NIL , 0 );
82+ }
7883 writeChunk (gen -> chunk , OP_RETURN , 0 );
7984
8085 ObjFunction * function = gen -> compiler -> function ;
@@ -376,7 +381,7 @@ static void genExpr(BytecodeGen* gen, Expr* expr) {
376381 genStmt (gen , expr -> as .lambda .body -> items [i ]);
377382 }
378383 }
379- ObjFunction * function = endCompiler (gen );
384+ ObjFunction * function = endCompiler (gen , false );
380385 Value funcVal = OBJ_VAL (function );
381386 int funcConst = addConstant (gen -> chunk , funcVal );
382387 writeChunk (gen -> chunk , OP_CLOSURE , expr -> line );
@@ -494,7 +499,8 @@ static void genFunction(BytecodeGen* gen, Stmt* stmt, bool defineVar) {
494499 }
495500 }
496501
497- ObjFunction * function = endCompiler (gen );
502+ bool isInit = (stmt -> as .func_decl .name != NULL && strcmp (stmt -> as .func_decl .name , "init" ) == 0 );
503+ ObjFunction * function = endCompiler (gen , isInit );
498504
499505 // Emit Closure
500506 Value funcVal = OBJ_VAL (function );
@@ -565,7 +571,13 @@ static void genStmt(BytecodeGen* gen, Stmt* stmt) {
565571 if (stmt -> as .return_stmt .value ) {
566572 genExpr (gen , stmt -> as .return_stmt .value );
567573 } else {
568- writeChunk (gen -> chunk , OP_NIL , stmt -> line );
574+ // Check if we are in init
575+ if (gen -> compiler -> function -> name != NULL && strcmp (gen -> compiler -> function -> name -> chars , "init" ) == 0 ) {
576+ writeChunk (gen -> chunk , OP_GET_LOCAL , stmt -> line );
577+ writeChunk (gen -> chunk , 0 , stmt -> line );
578+ } else {
579+ writeChunk (gen -> chunk , OP_NIL , stmt -> line );
580+ }
569581 }
570582 writeChunk (gen -> chunk , OP_RETURN , stmt -> line );
571583 break ;
0 commit comments