home ~ projects ~ socials

Split A Lua String On Newlines

function string:split(delimiter)
  local result = { }
  local from  = 1
  local delim_from, delim_to = string.find( self, delimiter, from  )
  while delim_from do
    table.insert( result, string.sub( self, from , delim_from-1 ) )
    from  = delim_to + 1
    delim_from, delim_to = string.find( self, delimiter, from  )
  end
  table.insert( result, string.sub( self, from  ) )
  return result
end


local input = [[alfa bravo

charlie delta
echo foxtrot]]

local lines = input:split("\n")

for _, line in ipairs(lines) do
  print("Found: " .. line)
end
Output:
Found: alfa bravo
Found: 
Found: charlie delta
Found: echo foxtrot
-- end of line --

References

I had a naive implenentaiton working which was great until I figured out that empty lines got eaten. This one is from someone who knows what they're doing. Bonus that you can use it to split with any delimeter.

I also like the approach of adding the function to string in general. I hadn't really seen that before