Lua 文件处理

Lua File Handling

我最近遇到这个错误:

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 ?

你可以在这个错误字符串中看到,它明确地告诉我们函数需要一个 string 并且它被提供了一个 FILE*(一个文件句柄)


Lua 编程是学习 Lua.

的重要资源