File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -184,6 +184,7 @@ static int emit_jump(u8 instruction)
184184
185185static void emit_return ()
186186{
187+ emit_byte (OP_NIL );
187188 emit_byte (OP_RETURN );
188189}
189190
@@ -796,6 +797,25 @@ static void print_statement()
796797 emit_byte (OP_PRINT );
797798}
798799
800+ static void return_statement ()
801+ {
802+ if (current -> type == TYPE_SCRIPT )
803+ {
804+ error ("Can't return from top-level code" );
805+ }
806+
807+ if (match (TOKEN_SEMICOLON ))
808+ {
809+ emit_return ();
810+ }
811+ else
812+ {
813+ expression ();
814+ consume (TOKEN_SEMICOLON , "Expect semicolon after return value;" );
815+ emit_byte (OP_RETURN );
816+ }
817+ }
818+
799819static void while_statement ()
800820{
801821 int loop_start = current_chunk ()-> count ;
@@ -865,6 +885,8 @@ static void statement()
865885 for_statement ();
866886 else if (match (TOKEN_IF ))
867887 if_statement ();
888+ else if (match (TOKEN_RETURN ))
889+ return_statement ();
868890 else if (match (TOKEN_WHILE ))
869891 while_statement ();
870892 else if (match (TOKEN_LEFT_BRACE ))
Original file line number Diff line number Diff line change @@ -323,7 +323,21 @@ static InterpretResult run()
323323 break ;
324324 }
325325 case OP_RETURN :
326- return INTERPRET_OK ;
326+ {
327+ Value result = pop ();
328+
329+ if (-- vm .frame_count == 0 )
330+ {
331+ pop ();
332+ return INTERPRET_OK ;
333+ }
334+
335+ vm .stack_top = frame -> slots ;
336+ push (result );
337+
338+ frame = & vm .frames [vm .frame_count - 1 ];
339+ break ;
340+ }
327341 }
328342 }
329343
You can’t perform that action at this time.
0 commit comments