在 Lua 中可以使用 io.open() 函数来判断文件是否存在。io.open() 函数会尝试打开一个文件,如果文件存在且可读,则返回一个文件句柄;如果文件不存在或不可读,则返回 nil。
示例代码如下:
local file = io.open("example.txt", "r")
if file then
print("File exists.")
io.close(file)
print("File does not exist.")
这段代码首先打开名为 "example.txt" 的文件,如果文件存在且可读,则输出 "File exists.",否则输出 "File does not exist."
需要注意的是,io.open() 函数需要调用 io.close() 来关闭文件句柄,以释放系统资源。