Skip to content

Instantly share code, notes, and snippets.

@Yagich
Last active September 17, 2021 13:58
Show Gist options
  • Save Yagich/162302a9b519157623f6836450c8ec0b to your computer and use it in GitHub Desktop.
Save Yagich/162302a9b519157623f6836450c8ec0b to your computer and use it in GitHub Desktop.
lua string splitting by delimiter, with limiting the result
function string:split(delimiter, max_matches)
-- Split a string by delimiter. The resulting table will be of size #max_matches.
max_matches = max_matches or #self
assert(max_matches > 0, "max_matches must be more than 0!")
local result = {}
local pos = 0
for vstart, vend in function() return string.find(self, delimiter, pos, true) end do
table.insert(result, string.sub(self, pos, vstart - 1))
pos = vend + 1
if #result >= max_matches - 1 then
table.insert(result, string.sub(self, pos))
return result
end
end
table.insert(result, string.sub(self, pos))
return result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment