Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if directory exists in lua?

How do I check if a directory exists in lua, preferably without using the LuaFileSystem module if possible?

Trying to do something like this python line:

os.path.isdir(path)
like image 330
Dan Avatar asked Aug 27 '09 10:08

Dan


3 Answers

This is a way that works on both Unix and Windows, without any external dependencies:

--- Check if a file or directory exists in this path
function exists(file)
   local ok, err, code = os.rename(file, file)
   if not ok then
      if code == 13 then
         -- Permission denied, but it exists
         return true
      end
   end
   return ok, err
end

--- Check if a directory exists in this path
function isdir(path)
   -- "/" works on both Unix and Windows
   return exists(path.."/")
end
like image 72
Hisham H M Avatar answered Nov 19 '22 04:11

Hisham H M


The problem is that the stock Lua distribution (nearly) only includes features that are specified in standard C. Standard C makes no presumptions about there actually being a file system of any specific sort out there (or even an operating system, for that matter), so the os and io modules don't provide access information not available from the standard C library.

If you were attempting to code in pure standard C, you would have the same issue.

There is a chance that you can learn whether the folder exists implicitly from an attempt to use it. If you expect it to exist and be writable to you, then create a temporary file there and if the that succeeds, the folder exists. If it fails, you might not be able to distinguish a non-existent folder from insufficient permissions, of course.

By far the lightest-weight answer to getting a specific answer would be a thin binding to just those OS-specific function calls that provide the information you need. If you can accept the lua alien module, then you can like do the binding in otherwise pure Lua.

Simpler, but slightly heavier, is to accept Lua File System. It provides a portable module that supports most things one might want to learn about files and the file system.

like image 14
RBerteig Avatar answered Nov 19 '22 03:11

RBerteig


If you're specifically interested in avoiding the LFS library, the Lua Posix library has an interface to stat().

require 'posix'
function isdir(fn)
    return (posix.stat(fn, "type") == 'directory')
end
like image 9
adrian Avatar answered Nov 19 '22 02:11

adrian