Lua 无法生成函数表(IO API)。

我正在 Lua 中开发一个基本项目。 我一直试图使用 IO API(如此处定义[http://www.lua.org/manual/5.1/manual.html#5.7])从文件中获取数据,但是当我打开文件并给它一个句柄时,它似乎没有返回一个函数表。

下面是有错误的代码:

local unread = fs.list("email/"..from.."/")
local send = ""
for _,file in ipairs(unread) do
    local handle = io.open(file,"r")
    local text = handle:read("*a")
    send = send .. text .. "\n"
    handle.close()
    fs.delete(file)
end

你看到的第一行的 fs 是一个专业的文件系统包装器,是 IO API 的一部分,不是我的工作,并且完全没有错误,所以这不是问题所在。 但是,当我尝试读取该文件(handle:read())时,它会抛出“尝试对nil索引”。跟踪它,结果发现 handle 本身是 nil。有什么想法吗?

点赞
用户869951
用户869951

io.open在成功时返回文件句柄,在失败时返回带有错误消息的nil(根据Lua参考手册)。这意味着你应该使用以下代码:

handle, err = io.open(file, 'r')
if handle == nil then
    print('could not open file:', file, ':', err)
    return
end
local text = handle:read("*a")
...

错误消息将告诉您是否没有读取文件的权限或者还存在其他问题。

2014-06-11 05:38:47