file - 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很陌生。我用谷歌搜索了这个错误,但没有找到任何可以帮助我解决这个问题的方法。
解决方案
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.
推荐阅读
- c# - 使用 Func 进行动态排序
, IOrderedQueryable > - python - Python Coverage 如何生成单元测试报告
- usb - Windows下USB Midi设备名称问题
- ms-access - Tableau MS_Access 未返回正确计数
- snowflake-cloud-data-platform - 从 Snowalert 到 Slack 或 AWS SNS 的 POP 警报数据
- sql - SQL-查找商店中最小产品的价格
- c++ - 是什么阻止编译器消除在每个特定上下文中未使用的数据成员?
- flutter - Dart/Flutter POST 请求和流响应
- matlab - matlab单引号?
- android - 错误:语言版本覆盖在库及其部分中必须相同