aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar BanceDev 2024-09-08 22:13:17 -0400
committerGravatar BanceDev 2024-09-08 22:13:17 -0400
commit6a2689d4ea04c79f7ef1fddf369dafbfd14e64e6 (patch)
treeb1c628a72a60cb91e04e8b095c911255e359f9bd
parentadded lua api functions for indexing history (diff)
added getenv and putenv to Lua API
fixed bug where terminal closed upon encountering Lua error
Diffstat (limited to '')
-rw-r--r--.lush/scripts/example.lua6
-rw-r--r--src/lua_api.c32
2 files changed, 33 insertions, 5 deletions
diff --git a/.lush/scripts/example.lua b/.lush/scripts/example.lua
index 53ee6e8..4d0b8fa 100644
--- a/.lush/scripts/example.lua
+++ b/.lush/scripts/example.lua
@@ -82,3 +82,9 @@ print("Most recent history: " .. lush.lastHistory())
-- you can also fetch history at a certain index in the past (1 being most recent)
print("Most recent history indexed: " .. lush.getHistory(1))
+
+-- you can set environment variables using putenv
+lush.putenv("EXAMPLE=Lunar Shell Example")
+
+-- you can get an environment variable using getenv
+print("Value of EXAMPLE: " .. lush.getenv("EXAMPLE"))
diff --git a/src/lua_api.c b/src/lua_api.c
index ac9bf30..e28d7c1 100644
--- a/src/lua_api.c
+++ b/src/lua_api.c
@@ -66,11 +66,16 @@ void lua_load_script(lua_State *L, const char *script, char **args) {
lua_setglobal(L, "args");
}
// if we got here the file exists
- if (luaL_dofile(L, script_path) != LUA_OK) {
- printf("[C] Error reading script\n");
- luaL_error(L, "Error: %s\n", lua_tostring(L, -1));
- // remove error from stack
- lua_pop(L, 1);
+ if (luaL_loadfile(L, script_path) == LUA_OK) {
+ if (lua_pcall(L, 0, LUA_MULTRET, 0) != LUA_OK) {
+ const char *error_msg = lua_tostring(L, -1);
+ fprintf(stderr, "[C] Error executing script: %s\n", error_msg);
+ lua_pop(L, 1); // remove error from stack
+ }
+ } else {
+ const char *error_msg = lua_tostring(L, -1);
+ fprintf(stderr, "[C] Error loading script: %s\n", error_msg);
+ lua_pop(L, 1); // remove error from stack
}
}
@@ -272,6 +277,19 @@ static int l_get_history(lua_State *L) {
return 1;
}
+static int l_get_env(lua_State *L) {
+ const char *env = luaL_checkstring(L, 1);
+ char *env_val = getenv(env);
+ lua_pushstring(L, env_val);
+ return 1;
+}
+
+static int l_put_env(lua_State *L) {
+ const char *env = luaL_checkstring(L, 1);
+ putenv((char *)env);
+ return 0;
+}
+
// -- register Lua functions --
void lua_register_api(lua_State *L) {
@@ -300,6 +318,10 @@ void lua_register_api(lua_State *L) {
lua_setfield(L, -2, "lastHistory");
lua_pushcfunction(L, l_get_history);
lua_setfield(L, -2, "getHistory");
+ lua_pushcfunction(L, l_get_env);
+ lua_setfield(L, -2, "getenv");
+ lua_pushcfunction(L, l_put_env);
+ lua_setfield(L, -2, "putenv");
// set the table as global
lua_setglobal(L, "lush");
}