简体   繁体   中英

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM