io.open 回傳值local file, err = io.open(path, "r")
if file then
file:close()
print("存在")
else
print("不存在: " .. err) -- "No such file or directory"
end
err = nil。nil、err 含錯誤訊息。local function file_exists(path)
local f = io.open(path, "rb") -- 二進位模式避免換行轉換
if f then f:close() end
return f ~= nil
end
-- 用法
if file_exists("/etc/nginx/nginx.conf") then
ngx.say("設定檔存在")
end
local lfs = require("lfs")
local function path_type(path)
local attr, err = lfs.attributes(path)
if not attr then return nil, err end -- 不存在
return attr.mode -- "file" / "directory" / "link" / "socket" ...
end
-- 用法
local t = path_type("/var/log")
if t == "directory" then print("是目錄") end
純 Lua 判斷存在性:**io.open(path, "rb") 即可**。需區分檔案/目錄型別時,引入 lua-filesystem (lfs) 取得 attributes。記得關閉檔案控制代碼,避免洩漏。