Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing multiline text files in Lua

I would like to know the best way to make my script write something into a file (lets say text.txt) in a way that would always add a line break at the end. When I append text using

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

twice, the file looks like:

hellohello

But I want it to look like:

hello
hello
like image 995
user2999071 Avatar asked Aug 09 '14 12:08

user2999071


2 Answers

Unlike print, the new line character isn't added automatically when calling io.write, you can add it yourself:

file:write("hello", "\n")
like image 63
Yu Hao Avatar answered Oct 17 '22 07:10

Yu Hao


The easiest way to achieve this would be to include a Newline character sequence every time you call the write method like so: file:write("hello\n") or so: file:write("hello", "\n"). This way, a script such as

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

would result in the desired output:

hello
hello

There are, however, many other solutions to this (some being more elegant than the others). When outputting text in Java, for example, there are special methods such as BufferedWriter#newLine(), which will do the same thing in a more cleaner fashion. So if your interested in a different way of achieving this, I suggest you read up on the Lua docs for analogous methods/solutions.

like image 45
Priidu Neemre Avatar answered Oct 17 '22 05:10

Priidu Neemre