【问题标题】:Save io.read() file reading result to a string将 io.read() 文件读取结果保存为字符串
【发布时间】:2021-08-27 19:37:31
【问题描述】:

所以我有一些代码:

  io.input(file)

  print(io.read())
  
  result = io.read()
  print(result)

  io.close(file)

当我运行它时,我得到了

dasdasd
nil

其中“dasdasd”是文件的内容。这对我来说意味着 io.read() 的结果没有正确地保存到字符串中。为什么会这样?我错过了什么?

【问题讨论】:

  • io.read() 从文件中读取下一行文本。 dasdasd 是文件的第一行,nil 表示没有第二行。

标签: string lua lua-table


【解决方案1】:

您假设read() 每次都回到开头。这将需要执行seek() 操作。 https://pgl.yoyo.org/luai/i/file%3Aseek

f  = io .input( 'filename.txt' )
print( f :read() )

f :seek('set')  --  set returns to the beginning
result  = f :read()
print( result )

f :close()

【讨论】:

    【解决方案2】:

    Lua 不是 referentially transparent 编程语言,io.read() 不是 pure function。如果你想多次调用它的输出,你不能只是多次调用它。将它保存到一个变量中并使用它(就像你在第一次调用它后立即做的那样)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多