Lua 標準庫無專用文件存在性檢查函數,**通用做法:嘗試以只讀模式打開,成功即存在**。本文給出 io.open 直接用法與可復用封裝函數。
local file, err = io.open("path/to/file", "r")
if file then
file:close()
print("文件存在")
else
print("文件不存在: ", err) -- "No such file or directory"
end
"r":只讀模式,文件必須存在。"rb":二進制只讀,跨平台更安全 (Windows 避免換行符轉換)。file (userdata 文件句柄) 或 nil + 錯誤信息字符串。
function file_exists(path)
local file = io.open(path, "rb")
if file then file:close() end
return file ~= nil
end
-- 用法
if file_exists("config.ini") then
load_config()
else
create_default_config()
end
Lua 無原生目錄檢查,**技巧:嘗試打開目錄路徑**,某些系統允許打開目錄獲取句柄,但行為不一致。跨平台建議:
os.execute + Shell 命令** (依賴平台):os.execute('test -d "' .. path .. '"') == 0 (Linux/macOS),os.execute('if exist "' .. path .. '\\nul" exit 0') (Windows)。lfs (LuaFileSystem) 庫** (推薦):lfs.attributes(path, "mode") == "directory"。io.popen('dir "'..path..'"')** 讀取輸出判斷 (Windows)。文件存在性:io.open(path, "rb") 封裝為 file_exists() 最簡可靠。 目錄檢查建議引入 lfs 庫或平台相關 Shell 命令。避免自造輪子,標準庫+成熟庫組合最穩健。