Last active
September 17, 2021 13:58
-
-
Save Yagich/162302a9b519157623f6836450c8ec0b to your computer and use it in GitHub Desktop.
lua string splitting by delimiter, with limiting the result
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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