The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Split A Lua String On Newlines

TODO: Pull subtitle into page object
Code
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
Results
Found: alfa bravo
Found: 
Found: charlie delta
Found: echo foxtrot

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Split A Lua String On Newlines 

-- code
-- lua

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


-- results/

Found: alfa bravo
Found: 
Found: charlie delta
Found: echo foxtrot

-- /results


-- ref
-- title: string.split.lua from jaredallard
-- url: https://gist.github.com/jaredallard/ddb152179831dd23b230

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

-- categories
-- Lua 

-- groups

-- metadata
-- date: 2023-10-25 15:45:41
-- id: 2xgl9090
-- site: aws
-- type: post
-- status: published