Is there any way to get a particular row in a string?

3

I have this example string:

s = [[Pão
com
Requeijão]]

Is there any way to get only the second line of the string? If so, how?

    
asked by anonymous 03.01.2018 / 20:28

3 answers

3

The second line of the string s is the result of s:match("\n(.-)\n") .

    
03.01.2018 / 22:13
1

Yes, there is.

On the moon the end of a line is signaled by \n , ie the solution is to break the line from the \n and pick up the second element. Here's how it would look:

if s:sub(-1) ~= "\n" then s = s.."\n" end --Garante que tenha um '\n' no final da linha
linhas = {} --Cria um array/table

for linha in string.gmatch(s, "(.-)\n") do --Itera sobre as linhas
    table.insert(linhas, linha) --Adiciona ao array linhas
end
  

See working at Ideone .

    
03.01.2018 / 20:59
1

I would split the string based on the rows and then pick up the second row by indexing the resulting table. Ex:

s=[[Pão
com
Requeijão]]

function split(str, sep)
    local ret = {}
    str = table.concat{str, sep}
    for part in string.gmatch(str, "(.-)" .. sep) do
        table.insert(ret, part)
    end
    return ret
end

lines = split(s, "\n")

print(lines[2])
    
03.01.2018 / 21:09