droppels
droppels

Reputation: 71

Read one line (and just one line) in Lua. How?

lets suppose that i have this .txt file:

this is line one
hello world
line three

in Lua, i want to creat a string only with the content of line two something like i want to get a specific line from this file and put into a string io.open('file.txt', 'r') -- reads only line two and put this into a string, like: local line2 = "hello world"

Upvotes: 2

Views: 3800

Answers (1)

Spar
Spar

Reputation: 1762

Lua files has the same methods as io library. That means files have read() with all options as well. Example:

local f = io.open("file.txt") -- 'r' is unnecessary because it's a default value.
print(f:read()) -- '*l' is unnecessary because it's a default value.
f:close()

If you want some specific line you can call f:read() and do nothing with it until you begin reading required line.

But more proper solution will be f:lines() iterator:

function ReadLine(f, line)
    local i = 1 -- line counter
    for l in f:lines() do -- lines iterator, "l" returns the line
        if i == line then return l end -- we found this line, return it
        i = i + 1 -- counting lines
    end
    return "" -- Doesn't have that line
end

Upvotes: 8

Related Questions