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?
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?
The second line of the string s
is the result of s:match("\n(.-)\n")
.
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 .
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])