检查文件是否存在

文件操作 / 基本操作

-- No exists function: try to open the file
local function file_exists(path)
  local file = io.open(path, "r")
  if file == nil then
    return false
  end
  file:close()
  return true
end

local file_name = "file.txt"
local out = assert(io.open(file_name, "w"))
out:write("Line 1\n")
out:close()

local has_file = file_exists(file_name)
-- has_file = true
local has_missing = file_exists("missing.txt")
-- has_missing = false

-- A directory opens too: this is not a file test
local has_dir = file_exists(".")
-- has_dir = true

print("has_file = " .. tostring(has_file))
print("has_missing = " .. tostring(has_missing))
print("has_dir = " .. tostring(has_dir))