Lua中file_exists函数无法检测同目录文件及语法报错问题
问题解决思路
1. 函数参数的语法错误
你第二个版本的函数定义function file_exists(test.txt)完全非法,Lua的函数参数名不能包含.——标识符只能由字母、数字、下划线组成,且不能以数字开头。这就是触发expected ) near .报错的原因,把参数名改回合法的标识符(比如name)即可解决这个语法问题。
2. 文件检测不到的核心原因及修复
第一个函数的问题在于硬编码了文件名,参数name完全没被使用,而且你可能忽略了:Lua脚本运行时的当前工作目录不一定是脚本本身所在的目录。
基础修复版本(使用传入参数)
让函数真正使用传入的文件名参数,调用时传入目标文件名:
function file_exists(name) local f = io.open(name, "r") if f ~= nil then io.close(f) logMsg("File exists") return true else logMsg("No file") return false end end -- 调用时传入要检测的文件名 file_exists("test.txt")
进阶修复版本(确保检测脚本同目录文件)
如果脚本运行时的工作目录不是脚本所在目录,需要先获取脚本自身路径,再拼接文件名:
-- 获取脚本所在目录的辅助函数 local function get_script_dir() local str = debug.getinfo(2, "S").source:sub(2) return str:match("(.*/)") or "./" end function file_exists_in_script_dir(filename) local script_dir = get_script_dir() local full_path = script_dir .. filename local f = io.open(full_path, "r") if f ~= nil then io.close(f) logMsg("File exists") return true else logMsg("No file") return false end end -- 调用检测脚本同目录下的test.txt file_exists_in_script_dir("test.txt")
3. 额外注意点
- 确认
test.txt确实存在于目标目录,且脚本拥有该文件的读取权限 - 调用函数时必须传入正确的文件名参数,不要让参数形同虚设
内容的提问来源于stack exchange,提问作者exp05
相关产品推荐
相关产品推荐

