Read LUA file

Asked

Viewed 125 times

2

I have a file that I just want to read some lines, not all lines. I 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 just these lines.

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 lines than the given range. In this case, you have to adapt the second way to interrupt the process if f:read() return nil (what’s a good idea anyway).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.