Writing multi-line text files in Lua

I would like to know how to make my script something in a file (say text.txt ) that always adds a line break at the end. When I add text using

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

twice, the file looks like this:

 hellohello 

But I want it to look like this:

 hello hello 
+7
file lua multiline line-breaks
source share
2 answers

Unlike print , a new line character is not added automatically when io.write called, you can add it yourself:

 file:write("hello", "\n") 
+7
source share

The easiest way to achieve this is to include the Newline character sequence each time you call the write method as follows: file:write("hello\n") or like this: file:write("hello", "\n") . Thus a script for example

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

will lead to the desired result:

 hello hello 

However, there are many other solutions for this (some of them are more elegant than others). For example, when outputting text in Java, there are special methods such as BufferedWriter#newLine() that will do the same in a cleaner way. Therefore, if you are interested in another way to achieve this, I suggest you familiarize yourself with the Lua docs for similar methods / solutions.

+3
source share

All Articles