Check if a file exists with Lua

2019-01-17 02:10发布

How can I check if a file exists using Lua?

9条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-17 03:04
IsFile = function(path)
print(io.open(path or '','r')~=nil and 'File exists' or 'No file exists on this path: '..(path=='' and 'empty path entered!' or (path or 'arg "path" wasn\'t define to function call!')))
end

IsFile()
IsFile('')
IsFIle('C:/Users/testuser/testfile.txt')

Looks good for testing your way. :)

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-17 03:05

You can also use the 'paths' package. Here's the link to the package

Then in Lua do:

require 'paths'

if paths.filep('your_desired_file_path') then
    print 'it exists'
else
    print 'it does not exist'
end
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-17 03:10

An answer which is windows only checks for files and folders, and also requires no additional packages. It returns true or false.

io.popen("if exist "..PathToFileOrFolder.." (echo 1)"):read'*l'=='1'

io.popen(...):read'*l' - executes a command in the command prompt and reads the result from the CMD stdout

if exist - CMD command to check if an object exists

(echo 1) - prints 1 to stdout of the command prompt

查看更多
登录 后发表回答