6

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?

1
  • I'm pretty sure f is going to be nil there, as trying to open a directory with io.open should return nil and a string like error opening "../web/": is a directory (on Windows I get ../web/: Permission denied) May 24, 2011 at 14:19

8 Answers 8

9

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.

7

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.

1
  • This will also return true for empty files.
    – blueyed
    Apr 15, 2015 at 23:54
6

if you do

local x,err=f:read(1)

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

2
  • 4
    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. May 14, 2010 at 16:32
  • 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
    May 14, 2010 at 22:39
5

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
1
  • 1
    This. Use LFS. In Soviet Lua, portability hurts YOU.
    – Puppy
    May 14, 2010 at 22:48
3

At least for UNIX:

if os.execute("cd '" .. f .. "'")
then print("Is a dir")
else print("Not a dir")
end

:)

0
function fs.isDir ( file )
if file == nil then return true end
if fs.exists(file) then
    os.execute("dir \""..userPath..file.."\" >> "..userPath.."\\Temp\\$temp")
    file = io.open(userPath.."\\Temp\\$temp","r")
    result = false
    for line in file:lines() do
        if string.find(line, "<DIR>") ~= nil then
            result = true
            break
        end
    end
    file:close()
    fs.delete("\\Temp\\$temp")
    if not (result == true or result == false) then
        return "Error"
    else
        return result
    end
else
    return false
end
end

This is some code I pulled from a library I found earlier.

2
  • Unfortunately no I do not. But I've found if you change the userPath variable to the directory that your project is in, make the Temp folder, and use it there should be no errors at all.
    – Marumaru
    Nov 2, 2012 at 21:10
  • hmmm - how can you pull something from a library and not know where you took it from? you should always give credit where credit is do.
    – Michael
    Nov 4, 2012 at 16:50
0

This checks first if the path can be read (which also is nil for empty files) and then checks that the size is not 0 additionally.

function is_dir(path)
    f = io.open(path)
    return not f:read(0) and f:seek("end") ~= 0
end
0

As the question doesn't specify the need of portability, on Linux/Unix systems you can relieve on file command:

function file(path)
  local p = io.popen(('file %q'):format(path))
  if p then
    local out = p:read():gsub('^[^:]-:%s*(%w+).*','%1')
    p:close()
    return out
  end
end

if file('/') == 'directory' then
  -- do something
end

Tested and worked from Lua 5.1 to 5.4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.