Commit fd12be99 authored by Nathaniel Wesley Filardo's avatar Nathaniel Wesley Filardo Committed by Terry Ellison
Browse files

file: list now takes optional pattern for filtering (#2452)

Thanks to @TerryE for many useful suggestions
parent 5d7a46ae
...@@ -214,18 +214,53 @@ static int file_open( lua_State* L ) ...@@ -214,18 +214,53 @@ static int file_open( lua_State* L )
static int file_list( lua_State* L ) static int file_list( lua_State* L )
{ {
vfs_dir *dir; vfs_dir *dir;
const char *pattern;
struct vfs_stat stat;
int pcres;
lua_settop(L, 1);
pattern = luaL_optstring(L, 1, NULL); /* Pattern (arg) or nil (not) at 1 */
dir = vfs_opendir("");
if (dir == NULL) {
return 0;
}
lua_newtable( L ); /* Table at 2 */
if (pattern) {
/*
* We know that pattern is a string, and so the "match" method will always
* exist. No need to check return value here
*/
luaL_getmetafield( L, 1, "match" ); /* Function at 3 */
}
if (dir = vfs_opendir("")) { while (vfs_readdir(dir, &stat) == VFS_RES_OK) {
lua_newtable( L ); if (pattern) {
struct vfs_stat stat; lua_settop( L, 3 ); /* Ensure nothing else on stack */
while (vfs_readdir(dir, &stat) == VFS_RES_OK) {
lua_pushinteger(L, stat.size); /* Construct and pcall(string.match,name,pattern) */
lua_setfield(L, -2, stat.name); lua_pushvalue( L, 3 );
lua_pushstring( L, stat.name );
lua_pushvalue( L, 1 );
pcres = lua_pcall( L, 2, 1, 0 );
if (pcres != 0) {
vfs_closedir(dir);
lua_error( L );
}
if (lua_isnil( L, -1 )) {
continue;
}
} }
vfs_closedir(dir); lua_pushinteger( L, stat.size );
return 1; lua_setfield( L, 2, stat.name );
} }
return 0;
/* Shed everything back to Table */
lua_settop( L, 2 );
vfs_closedir(dir);
return 1;
} }
static int get_file_obj( lua_State *L, int *argpos ) static int get_file_obj( lua_State *L, int *argpos )
......
...@@ -144,13 +144,17 @@ print("\nFile system info:\nTotal : "..total.." (k)Bytes\nUsed : "..used.." (k)B ...@@ -144,13 +144,17 @@ print("\nFile system info:\nTotal : "..total.." (k)Bytes\nUsed : "..used.." (k)B
Lists all files in the file system. Lists all files in the file system.
#### Syntax #### Syntax
`file.list()` `file.list([pattern])`
#### Parameters #### Parameters
none none
#### Returns #### Returns
a Lua table which contains the {file name: file size} pairs a Lua table which contains all {file name: file size} pairs, if no pattern
given. If a pattern is given, only those file names matching the pattern
(interpreted as a traditional [Lua pattern](https://www.lua.org/pil/20.2.html),
not, say, a UNIX shell glob) will be included in the resulting table.
`file.list` will throw any errors encountered during pattern matching.
#### Example #### Example
```lua ```lua
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment