From 48153edb5dbff0f370641d8b88ceae8f9e4f857f Mon Sep 17 00:00:00 2001 From: Guldoman Date: Wed, 9 Apr 2025 13:43:42 +0200 Subject: [PATCH] fix: don't go down the directory tree in `system.list_dir` (#2059) * fix: don't go down the directory tree in `system.list_dir` * feat: use `lua_rawlen` instead of `luaL_len` in `list_dir` callback Co-authored-by: Takase <20792268+takase1121@users.noreply.github.com> * refactor: remove unneeded `lua_pop` in `list_dir` Co-authored-by: Takase <20792268+takase1121@users.noreply.github.com> --------- Co-authored-by: Takase <20792268+takase1121@users.noreply.github.com> (cherry picked from commit e5a25dc6aa45e3ab4884c46066a447a27128f196) --- src/api/system.c | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/src/api/system.c b/src/api/system.c index fc10edb..bf85ecd 100644 --- a/src/api/system.c +++ b/src/api/system.c @@ -580,25 +580,24 @@ static int f_chdir(lua_State *L) { return 0; } +static SDL_EnumerationResult list_dir_enumeration_callback(void *userdata, const char *dirname, const char *fname) { + (void) dirname; + lua_State *L = userdata; + int len = lua_rawlen(L, -1); + lua_pushstring(L, fname); + lua_rawseti(L, -2, len + 1); + return SDL_ENUM_CONTINUE; +} static int f_list_dir(lua_State *L) { - int count = 0; const char *path = luaL_checkstring(L, 1); - char **dir = SDL_GlobDirectory(path, NULL, 0, &count); - if (!dir) { + lua_newtable(L); + bool res = SDL_EnumerateDirectory(path, list_dir_enumeration_callback, L); + if (!res) { lua_pushnil(L); lua_pushstring(L, SDL_GetError()); return 2; } - - lua_createtable(L, count, 0); - for (int ti = 1, i = 0; i < count; i++) { - if (strcmp(dir[i], ".") == 0) continue; - if (strcmp(dir[i], "..") == 0) continue; - lua_pushstring(L, dir[i]); - lua_rawseti(L, -2, ti++); - } - SDL_free(dir); return 1; }