Reputation: 113
This is what I'm trying to do:
io.open("__Equivalent-Exchange__/config/EMCfixed.lua", "r")
var1 = io.read(,*n)
Now I want to be able to set the row of the file that is specified with io.open
. What is found was this:
The reference manual state:
When called with a file name, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it simply sets this file handle as the default input file. When called without parameters, it returns the current default input file.
That didn't help me so I found the io.lines
piece.:
Opens the given file name in read mode and returns an iterator function that works like
file:lines(···)
over the opened file. When the iterator function detects the end of file, it returns no values (to finish the loop) and automatically closes the file.The call
io.lines()
(with no file name) is equivalent toio.input():lines("*l")
that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends."
BUT, How can I specify what line to read?
P.S. for other info on the topic I found this page, I didn't understand it. But it might help your in the process of helping me.
Upvotes: 1
Views: 4926
Reputation: 1967
You cannot jump directly to a specified line, because that would require you to know where that line is. Without reading the whole file up to at least this point, this is only possible if the lines have a fixed length (in which case you could use file:seek). However, if you do not have fixed-length lines, you'll have to iterate over the lines, counting as you go:
function getNthLine(fileName, n)
local f = io.open(fileName, "r")
local count = 1
for line in f:lines() do
if count == n then
f:close()
return line
end
count = count + 1
end
f:close()
error("Not enough lines in file!")
end
Edit: Note that you should not use this function if you are searching for multiple lines of the same file (e.g. you need lines 3, 5 and 8). In this case, the function above would open the file three times - that's a waste of system resources. Instead, you could define a function to be called on every number and check for matching line numbers there:
function checkLine(lineNumber, lineContent)
-- Disregard odd line numbers
if lineNumber % 2 == 0 then
-- do something with lineContent
end
end
local f = io.open(fileName, "r")
local count = 1
for line in f:lines() do
checkLine(count, line)
end
f:close()
Upvotes: 3