Reputation: 169
I have a txt file which stores data in the following format:
300
400
500
600
I was trying to read this file in a specific line, e.g. read(".txt",2) will return 500, I also try the following
cell.T = {} -- temperatures, K (as a table)
filename = "input.txt"
fp = io.open( filename, "r" )
local n=0
for line in fp:lines() do
n = n+1
if n == index_number then
cell.T[0]=line;
break;
end
end
fp:close()
My index_number is 0 1 2 3 respectively, but what I get is 0 300 400 500
something elsewhere should be wrong, but I don't know how to figure it out, can anyone have a look at this file?
Upvotes: 2
Views: 162
Reputation: 32894
The index_number
variable starts with 0
, but the code
local n=0
for line in fp:lines() do
n = n+1
if n == index_number then -- this condition will never be met when n = 0
shows that n
will never be 0
since it's incremented just before the check. Make the initialization like this
local n = -1
Or idiomatically, as indices start at 1
in Lua, you could change it to a post-increment
local n = 0
for line in fp:lines() do
if n == index_number then
-- do stuff
end
n = n + 1
end
Upvotes: 2