tags:

views:

201

answers:

4

If I have this code

local f = io.open("../web/", "r")
print(io.type(f))

-- output: file

how can I know if f points to a directory?

+6  A: 

ANSI C does not specify any way to obtain information on a directory, so vanilla Lua can't tell you that information (because Lua strives for 100% portability). However, you can use an external library such as LuaFileSystem to identify directories.

Progamming in Lua even explicitly states about the missing directory functionality:

As a more complex example, let us write a function that returns the contents of a given directory. Lua does not provide this function in its standard libraries, because ANSI C does not have functions for this job.

That example moves on to show you how to write a dir function in C yourself.

Mark Rushakoff
+4  A: 

Lua's default libraries don't have a way to determine this.

However, you could use the third-party LuaFileSystem library to gain access to more advanced file-system interactions; it's cross-platform as well.

Amber
This. Use LFS. In Soviet Lua, portability hurts YOU.
DeadMG
+3  A: 

if you do

local x,err=f:read(1)

then you'll get "Is a directory" in err.

lhf
Ha, that's really clever. :)
Pessimist
Note that the error message (if it comes from the system) may be localized, so it is probably not a very good idea to rely on it.
Alexander Gladysh
@Alexander: good point.
lhf
Of course, you might be able to collect reference samples of some localized system error messages by deliberately causing the errors at run time, and use that catalog to decide.... Now the problem is that the list of errors themselves is not really portable either. There might not even be a concept of directory in some standards compliant C environments, for instance.
RBerteig
+1 for simple and clever, however.
RBerteig
A: 

I've found this piece of code inside a library I use:

local ok, err, code = f:read("*a")
    f:close()
    if code == 21 then
        return true
    end

I don't know what the code would be in Windows, but on Linux/BSD/OSX it works fine.

Valerio Schiavoni