【问题标题】:Lua is refusing to read from a fileLua拒绝从文件中读取
【发布时间】:2021-12-19 12:30:44
【问题描述】:

我输入了我的代码,没想到它会在第一次尝试时工作,当然它没有。我不断调整它几个小时,但我一直得到相同的结果,直到我尽可能简单。

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

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

io.close(file)
print(test)

在得到(没有回报)之后,我决定休息一下,让其他人回答我的问题。

【问题讨论】:

    标签: lua emulation


    【解决方案1】:

    您的代码的问题是您试图从定义为输入文件的任何内容中读取。你只打开了一个文件,但你没有告诉 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 版本,读取格式为 *aa。我不记得在所有版本中是否都可以。至少手册是这么说的。

    【讨论】:

      猜你喜欢
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      相关资源
      最近更新 更多