Lua:收益率错误:尝试索引nil值(本地';f';)
我对Lua完全不熟悉,我需要使用一些Lua代码 我有下面的方法,在这里我传入一个文件,我想以字符串的形式读取该文件的内容Lua:收益率错误:尝试索引nil值(本地';f';),lua,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: [str
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")
知道是什么原因造成的吗?该错误意味着
io.open
失败。要了解原因,请尝试
local f = assert(io.open(file, "rb"))
或
因此,如果出现错误,它可以返回nil。示例fille或目录不存在,或者权限阻止文件被打开。该消息不来自Lua库。您使用的嵌入式Lua是什么程序?谢谢。现在我得到:
Lua:Yield error:尝试调用nil值(全局“assert”)
。我猜我应该导入一些包含assert
?@octavian的库,我不知道为什么assert
没有定义。尝试第二种形式。没错,基础文件不存在。你不会碰巧知道我需要导入什么才能使用assert
?@octavian,assert
是一个标准的Lua函数。它应该是可用的,但似乎承载Lua的程序已经选择删除它。
local f,e = io.open(file, "rb")
if f==nil then print(e) return nil end