Skip to content

Commit 6a6763a

Browse files
committed
feat: setenv
1 parent ba90b67 commit 6a6763a

1 file changed

Lines changed: 29 additions & 5 deletions

File tree

modules/os.c

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ static Value os_exec(VM* vm, int argCount, Value* args){
7676

7777
static Value os_system(VM* vm, int argCount, Value* args){
7878
if(argCount != 1 || !IS_STRING(args[0])){
79-
runtimeError(vm, "os.system expects a single string argument.\n");
79+
runtimeError(vm, "os.run expects a single string argument.\n");
8080
return NULL_VAL;
8181
}
8282

@@ -86,11 +86,11 @@ static Value os_system(VM* vm, int argCount, Value* args){
8686
#ifdef _WIN32
8787
return NUM_VAL((double)status);
8888
#else
89-
if(WIFEXITED(status) == 0){
90-
runtimeError(vm, "Failed to execute command: %s\n", strerror(errno));
91-
return NULL_VAL;
89+
if(WIFEXITED(status)){
90+
return NUM_VAL((double)WEXITSTATUS(status));
91+
}else{
92+
return NUM_VAL(-1);
9293
}
93-
return NUM_VAL((double)status);
9494
#endif
9595
}
9696

@@ -110,6 +110,29 @@ static Value os_getenv(VM* vm, int argCount, Value* args){
110110
return OBJECT_VAL(copyString(vm, value, (int)strlen(value)));
111111
}
112112

113+
static Value os_setenv(VM* vm, int argCount, Value* args){
114+
if(argCount != 2 || !IS_STRING(args[0]) || !IS_STRING(args[1])){
115+
runtimeError(vm, "os.setenv expects two string arguments: key and value.\n");
116+
return NULL_VAL;
117+
}
118+
119+
char* key = AS_CSTRING(args[0]);
120+
char* value = AS_CSTRING(args[1]);
121+
122+
int result = 0;
123+
124+
#ifdef _WIN32
125+
result = _putenv_s(key, value);
126+
#else
127+
result = setenv(key, value, 1);
128+
#endif
129+
if(result == 0){
130+
return BOOL_VAL(true);
131+
}else{
132+
return BOOL_VAL(false);
133+
}
134+
}
135+
113136
static Value os_exit(VM* vm, int argCount, Value* args){
114137
int exitCode = 0;
115138
if(argCount > 0 && IS_NUM(args[0])){
@@ -137,6 +160,7 @@ void registerOsModule(VM* vm){
137160
defineCFunc(vm, &module->members, "exec", os_exec);
138161
defineCFunc(vm, &module->members, "run", os_system);
139162
defineCFunc(vm, &module->members, "getenv", os_getenv);
163+
defineCFunc(vm, &module->members, "setenv", os_setenv);
140164
defineCFunc(vm, &module->members, "exit", os_exit);
141165

142166
tableSet(vm, &vm->modules, OBJECT_VAL(moduleName), OBJECT_VAL(module));

0 commit comments

Comments
 (0)