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

Thanks to @TerryE for many useful suggestions
This commit is contained in:
Nathaniel Wesley Filardo 2018-08-10 16:38:48 +01:00 committed by Terry Ellison
parent 5d7a46aec1
commit fd12be9966
2 changed files with 51 additions and 12 deletions

View File

@ -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;
if (dir = vfs_opendir("")) { lua_settop(L, 1);
lua_newtable( L ); pattern = luaL_optstring(L, 1, NULL); /* Pattern (arg) or nil (not) at 1 */
struct vfs_stat stat;
while (vfs_readdir(dir, &stat) == VFS_RES_OK) { dir = vfs_opendir("");
lua_pushinteger(L, stat.size); if (dir == NULL) {
lua_setfield(L, -2, stat.name); return 0;
}
vfs_closedir(dir);
return 1;
} }
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 */
}
while (vfs_readdir(dir, &stat) == VFS_RES_OK) {
if (pattern) {
lua_settop( L, 3 ); /* Ensure nothing else on stack */
/* Construct and pcall(string.match,name,pattern) */
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;
}
}
lua_pushinteger( L, stat.size );
lua_setfield( L, 2, stat.name );
}
/* 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 )

View File

@ -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