File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -218,6 +218,7 @@ static void mark_roots()
218218
219219 mark_table (& vm .globals );
220220 mark_compiler_roots ();
221+ mark_object ((Obj * )vm .init_string );
221222}
222223
223224static void trace_references ()
Original file line number Diff line number Diff line change @@ -63,6 +63,9 @@ void init_VM()
6363 init_table (& vm .globals );
6464 init_table (& vm .strings );
6565
66+ vm .init_string = NULL ;
67+ vm .init_string = copy_string ("init" , 4 );
68+
6669 vm .bytes_allocated = 0 ;
6770 vm .next_GC = 1024 * 1024 ;
6871
@@ -77,6 +80,7 @@ void free_VM()
7780{
7881 free_table (& vm .globals );
7982 free_table (& vm .strings );
83+ vm .init_string = NULL ;
8084 free_objects ();
8185}
8286
@@ -131,6 +135,18 @@ static bool call_value(Value callee, int arg_count)
131135 case OBJ_INSTANCE :
132136 ObjClass * klass = AS_CLASS (callee );
133137 vm .stack_top [- arg_count - 1 ] = OBJ_VAL (new_instance (klass ));
138+
139+ Value initializer ;
140+ if (table_get (& klass -> methods , vm .init_string , & initializer ))
141+ {
142+ return call (AS_CLOSURE (initializer ), arg_count );
143+ }
144+ else if (arg_count != 0 )
145+ {
146+ runtime_error ("Expected 0 arguments but got %d" , arg_count );
147+ return false;
148+ }
149+
134150 return true;
135151 case OBJ_CLOSURE :
136152 return call (AS_CLOSURE (callee ), arg_count );
Original file line number Diff line number Diff line change @@ -25,6 +25,7 @@ typedef struct
2525 Value * stack_top ;
2626 Table globals ;
2727 Table strings ; // for string interning just like (string pool in java)
28+ ObjString * init_string ;
2829 ObjUpvalue * open_upvalues ;
2930 size_t bytes_allocated ;
3031 size_t next_GC ;
You can’t perform that action at this time.
0 commit comments