尝试索引本地变量'file'(一个空值)?

我正在使用 corona 模拟器进行一个项目,该项目需要从项目目录中读取一些数据("car.csv"), 我有一段代码 supposed to 读取第一行,但当我运行它时,它会给我带来错误 "尝试索引本地变量'file'(一个空值)"。你有什么办法可以修复这个错误吗?

local function init()
    local path = system.pathForFile( "car.csv", system.DocumentsDirectory );
    local file = io.open(path, "r");
    line = file:read();
    print(line);
end

由于某种原因,它不会读入到 'file' 中。

编辑:好的,如果我使用完整路径而不是相对文件路径,它就可以了。但我需要使用相对路径,我不知道为什么它不起作用。

点赞
用户4984564
用户4984564

当使用 io.open 时,你应该始终确保它成功后才尝试读取文件,否则你会得到一个难看的 "attempt to index nil" 错误。

如果你想让你的程序仍然崩溃,只需执行以下命令:

local file = assert(io.open(path, 'r'))

如果文件找不到,它将为你提供一个更有用的错误消息。或者,你也可以手动保存 io.open 的返回值并检查错误:

local file, err, code = assert(io.open(path))
if not file then
   print("Error opening file", path, err)
   -- Do something to handle the error
end
2020-02-05 08:33:27