How can I check if a file exists using Lua?
相关问题
- How to get the return code of a shell script in lu
- Lazily Reading a File in D
- Check whether the path exists on server or not in
- Accessing Light userdata in Lua
- DirectoryStream.Filter example for listing files t
相关文章
- How to replace file-access references for a module
- Why is file_get_contents faster than memcache_get?
- Transactionally writing files in Node.js
- Getting the cluster size of a hard drive (through
- Example for file read/write with NSFileHandle
- Lua Integer type
- line-by-line file processing, for-loop vs with
- First character uppercase Lua
Try
but note that this code only tests whether the file can be opened for reading.
Using plain Lua, the best you can do is see if a file can be opened for read, as per LHF. This is almost always good enough. But if you want more, load the Lua POSIX library and check if
posix.stat(
path)
returns non-nil
.If you are willing to use
lfs
, you can uselfs.attributes
. It will returnnil
in case of error:Although it can return
nil
for other errors other than a non-existing file, if it doesn't returnnil
, the file certainly exists.I use:
I'm using LUA 5.3.4.
For sake of completeness: You may also just try your luck with
path.exists(filename)
. I'm not sure which Lua distributions actually have thispath
namespace (update: Penlight), but at least it is included in Torch:debug.getinfo(path.exists)
tells me that its source is intorch/install/share/lua/5.1/pl/path.lua
and it is implemented as follows:I will quote myself from here
I use these (but I actually check for the error):
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. If you dont want to use lfs you cant differentiate between files and directories without trying to open the file (which is a bit slow but ok).
So without LuaFileSystem
It looks shorter, but takes longer... Also open a file is a it risky
Have fun coding!