How to read a Bunch of files in a directory in lua

5.7k views Asked by At

I have a path (as a string) to a directory. In that directory, are a bunch of text files. I want to go to that directory open it, and go to each text file and read the data.

I've tried

f = io.open(path)
f:read("*a")

I get the error "nil Is a directory"

I've tried:

f = io.popen(path)

I get the error: "Permission denied"

Is it just me, but it seems to be a lot harder than it should be to do basic file io in lua?

2

There are 2 answers

2
Etan Reisner On

A directory isn't a file. You can't just open it.

And yes, lua itself has (intentionally) limited functionality.

You can use luafilesystem or luaposix and similar modules to get more features in this area.

1
Roberto Ierusalimschy On

You can also use the following script to list the names of the files in a given directory (assuming Unix/Posix):

dirname = '.'
f = io.popen('ls ' .. dirname)
for name in f:lines() do print(name) end