我最近收到此错误:
lua: Lua Testing.lua:36: bad argument #1 to 'read' (invalid option)
stack traceback:
[C]: in function 'read'
Lua Testing.lua:36: in main chunk
[C]: ?
我不知道为什么。这是我的代码:
file = assert(io.open("test.txt", "r"), "no file.")
print(io.read(file))
io.close(file)
为了解释一些事情,我使用断言来确保文件确实存在。 我对 Lua 还很陌生。我用谷歌搜索了这个错误,但没有找到任何可以帮助我解决这个问题的方法。
最佳答案
您错误地使用了io.open
的结果。
After you open a file, you can read from it or write to it with the methods read/write. They are similar to the read/write functions, but you call them as methods on the file handle, using the colon syntax. For instance, to open a file and read it all, you can use a chunk like this:
local f = assert(io.open(filename, "r")) local t = f:read("*all") f:close()
–Programming in Lua: 21.2 – The Complete I/O Model
此外,您没有收到很好的错误消息,我的 IDE 给了我:
so_test2.lua:2: bad argument #1 to 'read' (string expected, got FILE*)
stack traceback:
[C]: in function 'io.read'
so_test2.lua:2: in main chunk
[C]: in ?
您可以在这个错误字符串中看到,它具体告诉我们该函数需要一个字符串
,并且它提供了一个FILE*
(文件句柄)
Lua 编程是学习 Lua 时的绝佳资源。
关于file - Lua 文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66910340/