在 Lua 中读取一行(而且只是一行)。如何?

dro*_*els 2 lua

假设我有这个 .txt 文件:

this is line one
hello world
line three
Run Code Online (Sandbox Code Playgroud)

在Lua中,我想仅使用第二行的内容创建一个字符串,就像我想从该文件中获取特定行并将其放入字符串中 io.open('file.txt', 'r') -- 读取仅第二行并将其放入字符串中,例如:local line2 =“hello world”

Spa*_*par 8

Lua文件与库具有相同的方法io。这意味着文件read()也具有所有选项。例子:

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()
Run Code Online (Sandbox Code Playgroud)

如果您想要某些特定行,您可以调用 f:read() 并在开始读取所需行之前不执行任何操作。

但更合适的解决方案是f:lines()迭代器:

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
Run Code Online (Sandbox Code Playgroud)