Skip to content

Instantly share code, notes, and snippets.

@GabrielBdeC
Forked from jaredallard/string.split.lua
Last active February 1, 2021 21:05
Show Gist options
  • Save GabrielBdeC/b055af60707115cbc954b0751d87ec23 to your computer and use it in GitHub Desktop.
Save GabrielBdeC/b055af60707115cbc954b0751d87ec23 to your computer and use it in GitHub Desktop.
string.split in lua
--Returns a table splitting some string with a delimiter
--Changes to enhance the code from https://gist.github.com/jaredallard/ddb152179831dd23b230
function string:split(delimiter)
local result = {}
local from = 1
local delim_from, delim_to = string.find(self, delimiter, from, true)
while delim_from do
if (delim_from ~= 1) then
table.insert(result, string.sub(self, from, delim_from-1))
end
from = delim_to + 1
delim_from, delim_to = string.find(self, delimiter, from, true)
end
if (from <= #self) then table.insert(result, string.sub(self, from)) end
return result
end
@AntonPetrochenko
Copy link

Happened to pass by needing a lua string split polyfill. What exactly does this enhance from the original gist?

@GabrielBdeC
Copy link
Author

local example = '&$var.example.&$var'
example:split('&$var')

This will return '.example.' instead of ' ', '.example.', ' ' as before.
Alternatively, can be change to return '', '.example.', '' if pleased.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment