Last active
July 20, 2016 22:51
-
-
Save louiszuckerman/0708c572871c9129c087cd29d01834ec to your computer and use it in GitHub Desktop.
recursive & iterative string split functions in Lua
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
-- example: | |
-- split("a", "/") --=> {"a"} | |
-- split("a/b/", "/") --=> {"a", "b", ""} | |
-- 3rd argument in split_r should be omitted by caller | |
function split_r(str, delim, parts) | |
if not parts then | |
parts = {} | |
end | |
local pos = str:find(delim) | |
if not pos then | |
table.insert(parts, str) | |
return parts | |
else | |
table.insert(parts, str:sub(1, pos - 1)) | |
return split(str:sub(pos + 1), delim, parts) | |
end | |
end | |
function split_i(str, delim) | |
local parts = {} | |
local start = 1 | |
local find = 1 | |
while find do | |
find = str:find(delim, start) | |
if find then | |
table.insert(parts, str:sub(start, find - 1)) | |
start = find + 1 | |
else | |
table.insert(parts, str:sub(start)) | |
end | |
end | |
return parts | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment