Lua: Yield错误: 尝试对一个空值索引 (local 'f')

我对Lua完全不熟悉,但我需要与一些Lua代码一起工作。

我有以下方法,我传入一个文件,并希望将该文件的内容作为字符串读取。

function readAll(file)
    local io = require("io")
    local f = io.open(file, "rb")
    local content = f:read("*all")
    f:close()
    return content
end

但是,我得到了以下错误:

Lua: Yield错误: [string "myFile.lua"]:101: 尝试对一个空值索引 (local 'f')

该错误出现在这一行:

local content = f:read("*all")

有什么想法是什么导致这种错误的吗?

点赞
用户107090
用户107090

错误意味着 io.open 失败。要查看原因,请尝试以下代码:

local f = assert(io.open(file, "rb"))

或者

local f, e = io.open(file, "rb")
if f == nil then
    print(e)
    return nil
end
2017-09-19 13:55:44