From 2e26a0838c2c6a3af856d0275ae73941001b131c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Chlo=C3=A9=20Vulquin?= Date: Tue, 23 Jan 2024 00:22:44 +0100 Subject: [PATCH] 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 --- docs/api/system.lua | 8 ++++++++ src/api/system.c | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/docs/api/system.lua b/docs/api/system.lua index ae0f7424..792fa623 100644 --- a/docs/api/system.lua +++ b/docs/api/system.lua @@ -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 diff --git a/src/api/system.c b/src/api/system.c index da99f592..b13a7754 100644 --- a/src/api/system.c +++ b/src/api/system.c @@ -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 } };