Skip to content

Commit f3452a8

Browse files
committed
??
1 parent d4c4322 commit f3452a8

1 file changed

Lines changed: 26 additions & 2 deletions

File tree

osenv.c

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
#include <windows.h>
77
#endif
88

9-
static void clear_process_env(void) {
9+
static void clear_process_env(lua_State *L) {
1010
#ifdef _WIN32
1111
LPCH env = GetEnvironmentStringsA();
1212
if (!env) return;
@@ -25,6 +25,10 @@ static void clear_process_env(void) {
2525
key[len] = '\0';
2626

2727
SetEnvironmentVariableA(key, NULL);
28+
// sync CRT
29+
if (_putenv_s(key, "") != 0)
30+
return luaL_error(L, "failed to sync CRT env (putenv)");
31+
2832
free(key);
2933
}
3034
FreeEnvironmentStringsA(env);
@@ -59,6 +63,9 @@ static int env_unset(lua_State *L, const char *key) {
5963
#ifdef _WIN32
6064
if (!SetEnvironmentVariableA(key, NULL))
6165
return luaL_error(L, "failed to unset env var");
66+
// sync CRT
67+
if (_putenv_s(key, "") != 0)
68+
return luaL_error(L, "failed to sync CRT env (putenv)");
6269
#else
6370
if (unsetenv(key) != 0)
6471
return luaL_error(L, "failed to unset env var");
@@ -75,6 +82,9 @@ static int env_set(lua_State *L, const char *key, const char *val, const int for
7582
}
7683
if (!SetEnvironmentVariableA(key, val))
7784
return luaL_error(L, "failed to set env var");
85+
// sync CRT
86+
if (_putenv_s(key, val) != 0)
87+
return luaL_error(L, "failed to sync CRT env (putenv)");
7888
#else
7989
if (setenv(key, val, force) != 0)
8090
return luaL_error(L, "failed to set env var");
@@ -203,11 +213,25 @@ static int env__newindex(lua_State *L) {
203213
static int env__index(lua_State *L) {
204214
lua_settop(L, 2);
205215
const char *key = luaL_checkstring(L, 2);
216+
#ifdef _WIN32
217+
DWORD size = GetEnvironmentVariableA(key, NULL, 0);
218+
if (size == 0) {
219+
lua_pushnil(L);
220+
return 1;
221+
}
222+
char *buf = (char *)malloc(size);
223+
if (!buf) return luaL_error(L, "out of memory");
224+
GetEnvironmentVariableA(key, buf, size);
225+
lua_pushstring(L, buf);
226+
free(buf);
227+
#else
206228
const char *val = getenv(key);
207229
if (val)
208230
lua_pushstring(L, val);
209231
else
210232
lua_pushnil(L);
233+
#endif
234+
211235
return 1;
212236
}
213237

@@ -223,7 +247,7 @@ static int env__call(lua_State *L) {
223247
// env(table)
224248
luaL_checktype(L, 2, LUA_TTABLE);
225249

226-
if (nargs > 2 && lua_toboolean(L, 3)) clear_process_env();
250+
if (nargs > 2 && lua_toboolean(L, 3)) clear_process_env(L);
227251

228252
lua_pushnil(L);
229253
while (lua_next(L, 2) != 0) {

0 commit comments

Comments
 (0)