From 539a39f83a6a86b716a5856ec9b655323fd4fa43 Mon Sep 17 00:00:00 2001 From: sammyette <38820196+TorchedSammy@users.noreply.github.com> Date: Sat, 16 Oct 2021 13:47:39 -0400 Subject: [PATCH] feat: add fs.readdir function it takes 1 argument: the directory to read. --- golibs/fs/fs.go | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/golibs/fs/fs.go b/golibs/fs/fs.go index e607774..86b9e7e 100644 --- a/golibs/fs/fs.go +++ b/golibs/fs/fs.go @@ -30,6 +30,7 @@ var exports = map[string]lua.LGFunction{ "cd": fcd, "mkdir": fmkdir, "stat": fstat, + "readdir": freaddir, } // cd(dir) @@ -77,8 +78,32 @@ func fstat(L *lua.LState) int { path := L.CheckString(1) // TODO: handle error here - pathinfo, _ := os.Stat(path) + pathinfo, err := os.Stat(path) + if err != nil { + luaErr(L, err.Error()) + return 0 + } L.Push(luar.New(L, pathinfo)) return 1 } + +// readdir(dir) +// Returns a table of files in `dir` +func freaddir(L *lua.LState) int { + dir := L.CheckString(1) + names := []string{} + + dirEntries, err := os.ReadDir(dir) + if err != nil { + luaErr(L, err.Error()) + return 0 + } + for _, entry := range dirEntries { + names = append(names, entry.Name()) + } + + L.Push(luar.New(L, names)) + + return 1 +}