file = io.open("testRead.txt", "r")Now that the file testRead.txt has been opened, it is ready to be read. We will use the read() command to read a single line from the file into another variable.
ourline = file:read()This reads the first line of our text file. The next time we use the read() command it will read the second line. The next time, it would read the third line - and so on. Notice that we use the name of our file variable along with this command, separated by a colon. There are also some arguments you can use with file:read(). You can put any of the following arguments inside the parentheses with quotation marks.
file:close()
file = io.open("testRead.txt","r") for line in file:lines() do print(line) end file:close()
This code simply outputs the content of the file a line at a time, to the Output Pane (remember though that the Output Pane is only visible if you run a plugin the Plugin Editor).
file = io.open("testRead.txt","w") file:write("hello") file:close()
This time notice we used the w mode instead of r since we're writing, and not reading. We use file:write() with the text we want written to the file in parentheses and quotes. You could also use a variable instead. If you use a variable do not use quotation marks. Here's an example.
file = io.open("testRead.txt","w") myText = "Hello" file:write(myText) file:close()
You can use append mode so that when you write text to a file it gets added after all the text that is already in that file, instead of replacing it all. This is done in exactly the same way as the above, except that we use a mode, for append.
file = io.open("testRead.txt","a") myText = "\nHello" file:write(myText) file:close()
You may have noticed that this time, in the myText variable, we added \n inside the text string. This command is a line break, and will cause the text to go to the next line when written to our file. Some text file viewers may not display the line break correctly (it may be display on the same line as the surrounding text, as a little square), but technically it is a new line. The same method is used in C/C++.