Lua:产量错误:尝试索引零值(本地'f')

时间:2017-09-19 13:35:56

标签: lua

我对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 error: [string "myFile.lua"]:101: attempt to index a nil value (local 'f')

此行中出现错误:

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

知道可能导致这种情况的原因吗?

1 个答案:

答案 0 :(得分:2)

错误表示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