Lua - File Iterator
We can process content of a file without loading it completely using iterators either line by line or even word by word. Lua provides io.lines method to iterate over lines of a file.
Using iterator to read file Line by Line
In this example, we're calling io.lines within a for loop. Lua automatically opens the file, creates an iterator and close the file once loop is finished.
we will use a sample file example.txt as shown below−
example.txt
Welcome to tutorialspoint.com Simply Easy Learning
main.lua
for line in io.lines("example.txt") do
print(line)
end
Output
When the above code is built and executed, it produces the following result −
Welcome to tutorialspoint.com Simply Easy Learning
Explanation
io.lines("example.txt") returns an iterator to iterate over lines of the file.
for loop read the next line from file everytime it calls the iterator and returns it.
for loop continues till end of the file where iterator returns nil and loop finishes.
Using line variable within for loop and each line is printed using print(line) statement.
Using iterator to read file Word by Word
In this example, we're combining io.lines call within a for loop with a nested for loop with string.gmatch to match a word for pattern. This way we can read files as words instead of lines.
we will use a sample file example.txt as shown below−
example.txt
Welcome to tutorialspoint.com Simply Easy Learning
main.lua
for line in io.lines("example.txt") do
for word in string.gmatch(line, "%w+") do
print(word)
end
end
Output
When the above code is built and executed, it produces the following result −
Welcome to tutorialspoint com Simply Easy Learning
Explanation
io.lines("example.txt") returns an iterator to iterate over lines of the file.
for loop read the next line from file everytime it calls the iterator and returns it.
Nested for loop gets the itertor of words splitted from the line.
Using word variable within nested for loop and each word is printed using print(word) statement.
Advantages of File Iterators
Memory Efficiency − As we're processing a file line by line, entire file is not loaded into the memory and we can read every very large files easily using such iterators.
Improved Code Readability − for...in loop is easy to understand and a very concise representation of iteration code.
Flexibility − We can modulate code easily to process a file line by line or word by word as per our convenience.