aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar BanceDev 2024-09-11 15:42:49 -0400
committerGravatar BanceDev 2024-09-11 15:42:49 -0400
commit0381ae7467e992f77ee7163402d97e2e14557398 (patch)
treec391d22aca47aa7f153878ae1f8b3d2445afa43a
parentv0.1.0 (diff)
added glob function to lua APi
-rw-r--r--.lush/scripts/example.lua10
-rw-r--r--src/lua_api.c43
2 files changed, 53 insertions, 0 deletions
diff --git a/.lush/scripts/example.lua b/.lush/scripts/example.lua
index 0239500..b3de3cb 100644
--- a/.lush/scripts/example.lua
+++ b/.lush/scripts/example.lua
@@ -96,3 +96,13 @@ lush.unsetenv("EXAMPLE")
-- this function is very useful if you want to make certain kinds of custom prompts in your init.lua
print("Terminal Columns: " .. lush.termCols())
print("Terminal Rows: " .. lush.termRows())
+
+-- the glob function scans the current working directory for files with the given extension and returns
+-- them as an array of strings
+local textFiles = lush.glob("txt")
+if textFiles ~= nil then
+ print("Printing txt files:")
+ for i = 1, #textFiles do
+ print(textFiles[i])
+ end
+end
diff --git a/src/lua_api.c b/src/lua_api.c
index f58fba7..20f089c 100644
--- a/src/lua_api.c
+++ b/src/lua_api.c
@@ -18,6 +18,7 @@ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#include "lua_api.h"
#include "history.h"
#include "lush.h"
+#include <dirent.h>
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
@@ -357,6 +358,46 @@ static int l_terminal_rows(lua_State *L) {
return 1;
}
+static int l_glob(lua_State *L) {
+ const char *ext = luaL_checkstring(L, 1);
+ DIR *dir;
+ struct dirent *entry;
+ size_t size = 0;
+
+ // Open the current directory
+ dir = opendir(".");
+ if (dir == NULL) {
+ perror("Unable to open current directory");
+ return 0;
+ }
+
+ // Create a Lua table for the results
+ lua_newtable(L);
+
+ // Read each directory entry
+ while ((entry = readdir(dir)) != NULL) {
+ const char *last_dot = strrchr(entry->d_name, '.');
+
+ // Only process files with extensions
+ if (last_dot != NULL) {
+ last_dot++; // Move past dot to the extension
+
+ // Check if the extension matches the input argument
+ if (strcmp(last_dot, ext) == 0) {
+ lua_pushstring(L, entry->d_name);
+ lua_rawseti(L, -2, size + 1);
+ size++;
+ }
+ }
+ }
+
+ // Close the directory
+ closedir(dir);
+
+ // Return the table with matching filenames
+ return 1;
+}
+
// -- register Lua functions --
void lua_register_api(lua_State *L) {
@@ -399,6 +440,8 @@ void lua_register_api(lua_State *L) {
lua_setfield(L, -2, "termCols");
lua_pushcfunction(L, l_terminal_rows);
lua_setfield(L, -2, "termRows");
+ lua_pushcfunction(L, l_glob);
+ lua_setfield(L, -2, "glob");
// set the table as global
lua_setglobal(L, "lush");
}