Add system.setenv (#1706)

* add system.setenv

* document system.setenv

* system.setenv: use wide versions of functions on windows

* do not include processenv.h

* system.setenv: report failure, including of utfconv

* system.setenv: free utfconv output
This commit is contained in:
Chloé Vulquin 2024-01-23 00:22:44 +01:00 committed by George Sokianos
parent 5ce34eb74c
commit 2e26a0838c
2 changed files with 29 additions and 0 deletions

View File

@ -324,5 +324,13 @@ function system.load_native_plugin(name, path) end
---@return boolean compare_result True if path1 < path2
function system.path_compare(path1, type1, path2, type2) end
---
---Sets an environment variable.
---The converse of os.getenv.
---
---@param key string
---@param val string
---@return boolean ok True if call succeeded
function system.setenv(key, val) end
return system

View File

@ -1150,6 +1150,26 @@ static int f_text_input(lua_State* L) {
return 0;
}
static int f_setenv(lua_State* L) {
const char *key = luaL_checkstring(L, 1);
const char *val = luaL_checkstring(L, 2);
int ok;
#ifdef _WIN32
LPWSTR wkey = utfconv_utf8towc(key);
LPWSTR wval = utfconv_utf8towc(val);
ok = (wkey && wval) ? SetEnvironmentVariableW(wkey, wval)
/* utfconv error */ : 0;
free(wkey); free(wval);
#else
// right now we overwrite unconditionally
// this could be expanded later as an optional 3rd boolean argument
ok = !setenv(key, val, 1);
#endif
lua_pushboolean(L, ok);
return 1;
}
static const luaL_Reg lib[] = {
{ "poll_event", f_poll_event },
@ -1185,6 +1205,7 @@ static const luaL_Reg lib[] = {
{ "path_compare", f_path_compare },
{ "get_fs_type", f_get_fs_type },
{ "text_input", f_text_input },
{ "setenv", f_setenv },
{ NULL, NULL }
};