Lua: Reading Text Documents and Using Tail Calls
Reading text documents
This lesson is about reading .txt documents, this is pretty simple in lua.
Here is the basic (heavily commented) code for reading .txt files (and .log files, and some others):
filename = "Test.txt" --Set variable 'filename' to the files name
file = assert(io.open(filename, "r")) --assert helps us with error handling
stringOne = file:read("*all") --read the whole file
print("Whole thing:\n\n"..stringOne) --Output the whole file
file:seek("set") --Bring the file to the start (so it knows which line to read)
stringTwo = file:read("*line") --Read only one line (wherever is set)
print("\n\nSingle line:\n"..stringTwo) --Output the line from the file
Basically the "io.open" is the bit that really opens the file, then we just mess around with it from there..As the program currently is, it will open a .txt file named 'Test.txt' in the folder that the .lua file itself is stored in; This usually does the job, but sometimes you might want a fixed location like so:
filename = "C:/Test.txt"
Obviously in the case above the file is called 'Test.txt' and is in the C drive.
Reading text files can be extremely useful, and as you can see, you can output the whole file, or just the one line..
Tail calls
Tail calls are basically just another one of those useful little things in lua (which you will eventually know a lot of, since they keep being featured along with lessons).
All a tail call is, is a function which calls another function as its last action; This is always very useful, and I use it a lot when programming in lua; Here is an example of a tail call:
function PrintFile(PrintMe)
print(PrintMe)
end
function ReadFile(filename)
file = assert(io.open(filename, "r"))
FileContent = file:read("*all")
return PrintFile(FileContent)
end
ReadFile("Test.txt")
Back to Lua

