Read LUA file

2

I have a file that I want to read only a few lines, not all lines. I get by GET the lines I want to read, which are numbers. I can only read the entire file.

local inicio = GET["inicio"]
local fim = GET["fim"]
local f = io.open(ficheiro, "r" ) --ler ficheiro
for line in f:lines() do --correr lignas
    --insert table 
    table.insert(dat_array, line)
end

For example if the beginning is 2 and the end 6, read in the cycle is only those lines.

    
asked by anonymous 06.02.2015 / 10:56

1 answer

4

A way:

local l=0
for line in f:lines() do
    l=l+1
    if l>=inicio and l<=fim then
        table.insert(dat_array, line)
    end
    if l>=fim then break end
end
f:close()

Another way:

for l=1,inicio-1 do
    f:read()
end
for l=inicio,fim do
    table.insert(dat_array, f:read())
end
f:close()

The first way works even if the file has fewer rows than the given range. In this case, you have to adapt the second way to stop the process if f:read() returns nil (which is a good idea anyway).

    
06.02.2015 / 11:17