@@ -68,6 +68,23 @@ static Value native_pop(int argCount, Value* args) {
6868 return list -> items [-- list -> count ];
6969}
7070
71+ static Value native_substr (int argCount , Value * args ) {
72+ if (argCount < 3 ) return NIL_VAL ;
73+ if (!IS_STRING (args [0 ]) || !IS_NUMBER (args [1 ]) || !IS_NUMBER (args [2 ])) return NIL_VAL ;
74+
75+ ObjString * source = AS_STRING (args [0 ]);
76+ int start = (int )AS_NUMBER (args [1 ]);
77+ int length = (int )AS_NUMBER (args [2 ]);
78+
79+ if (start < 0 || start >= source -> length ) {
80+ return OBJ_VAL (copyString ("" , 0 ));
81+ }
82+ if (length < 0 ) length = 0 ;
83+ if (start + length > source -> length ) length = source -> length - start ;
84+
85+ return OBJ_VAL (copyString (source -> chars + start , length ));
86+ }
87+
7188/*
7289 * Register all standard library modules
7390 * Called during VM initialization
@@ -217,4 +234,5 @@ void registerStdLib(VM* vm) {
217234 defineNative (vm , "list_push" , native_push );
218235 defineNative (vm , "limit_pop" , native_pop ); // wait, list_pop
219236 defineNative (vm , "list_pop" , native_pop );
237+ defineNative (vm , "substr" , native_substr );
220238}
0 commit comments