在Lua中编写多行文本文件

我想知道如何以一种始终在末尾添加换行符的方式,将一些文本写入文件(比方说 text.txt)中。当我使用

file = io.open("test.txt", "a")
file:write("hello")

两次时,文件看起来像这样:

hellohello

但我希望它看起来像这样:

hello
hello
点赞
用户1009479
用户1009479

print 不同,调用 io.write 不会自动添加换行符,您需要自行添加:

file:write("hello", "\n")
2014-08-09 12:38:05
用户1021943
用户1021943

最简单的方法是在每次调用“write”方法时包含一个Newline字符序列,如: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文档,了解类似的方法/解决方案。

2014-08-09 12:55:24