How to Check if a Directory Exists in Lua (and in Python)


Lua language logo

 
Checking if a directory exists in pure Lua is actually not an easy thing. Lua does not have the functions to get information about the file system and directories. You can test if a particular file exists in a folder by trying to open it (but the test can fail even if the folder exists…).

One way to properly check if a directory exists is to use the LFS library. The LFS (LuaFileSystem) library works on Unix and Windows and offers functions to access the underlying directory structure and file attributes. With LFS, we can easily check if a folder exists:

function dir_exists_v1(path)
  if (lfs.attributes(path, "mode") == "directory") then
    return true
  end
  return false
end

The LFS library is available in GeeXLab. Just use the lfs library name in your Lua scripts.

In the startup demo of GeeXLab, the dir_exists() function based on LFS is used to check if the demos/ folder exists (in frame.lua) in order to display the Demos folder button:

local app_dir = gh_utils.get_app_dir()
local demos_dir = app_dir .. "/demos/"
if (dir_exists_v1(demos_dir)) then
  ...
end

 
Another way to check the existence of a directory is to use the rename function of Lua’s os library: os.rename() (based on this stackoverflow reply). Here is the dir_exists() function with os.rename():

function file_exists_v2(file)
  -- some error codes:
  -- 13 : EACCES - Permission denied
  -- 17 : EEXIST - File exists
  -- 20	: ENOTDIR - Not a directory
  -- 21	: EISDIR - Is a directory
  --
  local isok, errstr, errcode = os.rename(file, file)
  if isok == nil then
     if errcode == 13 then 
        -- Permission denied, but it exists
        return true
     end
     return false
  end
  return true
end
 
function dir_exists_v2(path)
  return file_exists(path .. "/")
end

This function dir_exists_v2() works fine but is slower than dir_exists_v1().

 
And just for fun, here is the Python version of dir_exists() 😀 😀

def dir_exists(path):
  return os.path.isdir(path)

More on os.path here.





Leave a Comment

Your email address will not be published. Required fields are marked *