检查文件是否存在

文件操作 / 基本操作

-- 没有 exists 函数:尝试打开文件
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

-- 目录也能打开:所以这不是对文件的判断
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))