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
Unlike print
, the new line character isn't added automatically when calling io.write
, you can add it yourself:
file:write("hello", "\n")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With