Checking if a directory exists

Lua:
Checking if a directory exists

How to:

In Lua, you don’t have a built-in function to directly check if a directory exists, so you often rely on the Lua File System (lfs) library, a popular third-party library for file operations.

First, ensure you have Lua File System installed. If not, you can generally install it using LuaRocks:

luarocks install luafilesystem

Then, you can use the following example to check for a directory’s existence:

local lfs = require "lfs"

function directoryExists(directory)
    local attr = lfs.attributes(directory)
    return attr and attr.mode == "directory"
end

-- Check if a specific directory exists
if directoryExists("/path/to/your/directory") then
    print("Directory exists.")
else
    print("Directory does not exist.")
end

This will output:

Directory exists.

Or, if the directory doesn’t exist:

Directory does not exist.

This approach uses the lfs.attributes function to get the attributes of the path. If the path exists and its mode attribute is directory, it confirms the directory’s existence.