SoFunction
Updated on 2025-04-08

Lua method to determine whether a directory or file exists

1. Use

Open it all in one go.

Copy the codeThe code is as follows:

file,err=("XXXX")

If the file is open normally, file is the file handle, err is nil. Otherwise file is nil and err is the error message "drr: No such file or directory".


Just open it. Then look at the return value.

Copy the codeThe code is as follows:

somefile=""
local F,err=(somefile,"r+");
print(err)

If the file does not exist, err will contain relevant information.

2. Custom functions

Copy the codeThe code is as follows:

function file_exists(path)
  local file = (path, "rb")
  if file then file:close() end
  return file ~= nil
end