Lua拒绝从文件中读取数据。

3

我打出了代码,没想到第一次就能成功,当然失败了。我不停地调整了几个小时,但一直得到相同的结果,直到我尽可能地简化它为止。

local file = io.open("File_Name", "r")
io.output(file)

local test = io.read('*all')

io.close(file)
print(test)

在得不到任何回应之后,我决定休息一下,让其他人来回答我的问题。
1个回答

2
你的代码问题在于你试图从被定义为输入文件的任何地方读取。你只是打开了一个文件,但你没有告诉Lua将其用作输入文件,所以io.read不会从打开的文件中读取。
local file = io.open(filename, "r")
local test = file:read("a")
io.close(file)
print(test)

或者:

local file = io.open(filename, "r")
io.input(file)
local test = io.read("a")
io.close(file)
print(test)

或者

local file = io.open(filename, "r")    
local test = io.input(file):read("a")
io.close(file)
print(test)

在使用文件句柄之前,当然应该检查打开文件是否成功。

根据您的Lua版本,读取格式要么是*a,要么是a。我不记得在所有版本中都可以使用两者。至少手册上是这样说的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接