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)
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)
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.
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
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
Well, the 5.1 reference manual doesn't have anything in the os table, but if you use Nixstaller, you get os.fileexists
for precisely what you've explained.
If you can afford to fiddle around a bit, or if you know what OS you'll be running on, you might get away with the standard os library's os.execute
with some system call that will identify if the file exists.
Even better than os.execute might be os.rename:
os.rename(oldname, newname)
Renames file named
oldname
tonewname
. If this function fails, it returns nil, plus a string describing the error.
You could try setting oldname and newname the same -- you might not have write permissions, though, so it might fail because you can't write, even though you can read. In that event, you'd have to parse the returned error string and deduce whether you could write, or you'd have to just try executing your function that needs an existing file, and wrap it in a pcall
.
You can also use the 'paths' package. Here's the link to the package
Then in Lua do:
require 'paths'
if paths.dirp('your_desired_directory') then
print 'it exists'
else
print 'it does not exist'
end
This is tested for the windows platform. It is quite easy actually:
local function directory_exists( sPath )
if type( sPath ) ~= "string" then return false end
local response = os.execute( "cd " .. sPath )
if response == 0 then
return true
end
return false
end
Obviously, this may not work on other OS's. But for windows users, this can be a solution :)
here is a simple way to check if a folder exists WITHOUT ANY EXTERNAL LIBRARY DEPENDENCIES :)
function directory_exists(path)
local f = io.popen("cd " .. path)
local ff = f:read("*all")
if (ff:find("ItemNotFoundException")) then
return false
else
return true
end
end
print(directory_exists("C:\\Users"))
print(directory_exists("C:\\ThisFolder\\IsNotHere"))
If you copy and paste the above into Lua you should see
false
true
good luck :)
I use these (but i actually check for the error):
require("lfs")
-- no function checks for errors.
-- you should check for them
function isFile(name)
if type(name)~="string" then return false end
if not isDir(name) then
return os.rename(name,name) and true or false
-- note that the short evaluation is to
-- return false instead of a possible nil
end
return false
end
function isFileOrDir(name)
if type(name)~="string" then return false end
return os.rename(name, name) and true or false
end
function isDir(name)
if type(name)~="string" then return false end
local cd = lfs.currentdir()
local is = lfs.chdir(name) and true or false
lfs.chdir(cd)
return is
end
os.rename(name1, name2) will rename name1 to name2. Use the same name and nothing should change (except there is a badass error). If everything worked out good it returns true, else it returns nil and the errormessage. You said you dont want to use lfs. If you dont you cant differentiate between files and directorys without trying to open the file (which is a bit slow but ok).
So without LuaFileSystem
-- no require("lfs")
function exists(name)
if type(name)~="string" then return false end
return os.rename(name,name) and true or false
end
function isFile(name)
if type(name)~="string" then return false end
if not exists(name) then return false end
local f = io.open(name)
if f then
f:close()
return true
end
return false
end
function isDir(name)
return (exists(name) and not isFile(name))
end
It looks shorter, but takes longer... Also open a file is a it risky, because of that you should use lfs. If you don't care about performance (and errorhandling -.-) you can just use it.
Have fun coding!
My preferred way of doing this in linux is
if os.execute '[ -e "/home" ]' then
io.write "it exists"
if os.execute '[ -d "/home" ]' then
io.write " and is a directory"
end
io.write "\n"
end
or, to put this into a function:
function is_dir(path)
return os.execute(('[ -d "%s" ]'):format(path))
end -- note that this implementation will return some more values
For Linux users:
function dir_exists( path )
if type( path ) ~= 'string' then
error('input error')
return false
end
local response = os.execute( 'cd ' .. path )
if response == nil then
return false
end
return response
end