file - Lua 文件处理

标签 file lua io

我最近收到此错误:

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/

相关文章:

c++ - 从文件读取到字符串无法按预期工作

file - 如何从文件中删除最后 N 个字节

lua - Corona sdk线性色带?

lua - 如何获取lua中参数的名称?

windows - 检查在 Linux 和 Windows 中保存文件的进程

c++ - C++ 中的运算符重载 <<

c# - 使用 AES 在 C# 中安全传输文件

java - 从jar文件编译和运行时读取文件差异

python - 在Python中: How to Return "Windows" Created Time of a File?

c++ - 调试嵌入式 Lua