Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lua, check if file is a directory

Tags:

lua

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?

like image 333
PeterMmm Avatar asked May 14 '10 11:05

PeterMmm


4 Answers

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.

like image 124
Mark Rushakoff Avatar answered Nov 05 '22 06:11

Mark Rushakoff


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

function is_dir(path)
    local f = io.open(path, "r")
    local ok, err, code = f:read(1)
    f:close()
    return code == 21
end

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

like image 27
Valerio Schiavoni Avatar answered Nov 05 '22 04:11

Valerio Schiavoni


if you do

local x,err=f:read(1)

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

like image 6
lhf Avatar answered Nov 05 '22 04:11

lhf


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.

LuaFileSystem provides lfs.attributes which you can use to query the file mode:

require "lfs"
function is_dir(path)
    -- lfs.attributes will error on a filename ending in '/'
    return path:sub(-1) == "/" or lfs.attributes(path, "mode") == "directory"
end
like image 5
Amber Avatar answered Nov 05 '22 05:11

Amber