首页 > 解决方案 > Lua 文件处理

问题描述

我最近收到此错误:

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)

为了解释一些事情,我使用 assert 来确保文件存在并且它存在。我对Lua很陌生。我用谷歌搜索了这个错误,但没有找到任何可以帮助我解决这个问题的方法。

标签: fileluaio

解决方案


You are using the result of io.open incorrectly.

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()

–<a href="https://www.lua.org/pil/21.2.html" rel="nofollow noreferrer">Programming in Lua: 21.2 – The Complete I/O Model


Also you did not get a very good error message, my IDE gave me:

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 ?

You can see in this error string, it tells us specifically that the function expected a string and it was provided a FILE*(a file handle)


Programming in Lua is a great resource while learning Lua.


推荐阅读