【发布时间】:2014-08-09 12:18:20
【问题描述】:
我想知道让我的脚本以始终在末尾添加换行符的方式将某些内容写入文件(比如说text.txt)的最佳方法。当我使用
file = io.open("test.txt", "a")
file:write("hello")
两次,文件看起来像:
hellohello
但我希望它看起来像:
hello
hello
【问题讨论】:
标签: file lua line-breaks multiline
我想知道让我的脚本以始终在末尾添加换行符的方式将某些内容写入文件(比如说text.txt)的最佳方法。当我使用
file = io.open("test.txt", "a")
file:write("hello")
两次,文件看起来像:
hellohello
但我希望它看起来像:
hello
hello
【问题讨论】:
标签: file lua line-breaks multiline
与print不同,调用io.write时不会自动添加换行符,您可以自己添加:
file:write("hello", "\n")
【讨论】:
实现这一点的最简单方法是在每次调用 write 方法时都包含一个 Newline character sequence,如下所示:file:write("hello\n") 左右:file:write("hello", "\n")。这样,脚本如
file = io.open(test.txt, "a")
file:write("hello", "\n")
file:write("hello", "\n")
将产生所需的输出:
hello
hello
但是,还有许多其他解决方案(有些比其他解决方案更优雅)。例如,在 Java 中输出文本时,有一些特殊的方法,例如 BufferedWriter#newLine(),它们会以更简洁的方式执行相同的操作。因此,如果您对实现此目的的不同方式感兴趣,我建议您阅读 Lua 文档以了解类似的方法/解决方案。
【讨论】: