mirror of
https://github.com/1bardesign/batteries.git
synced 2024-11-10 02:31:48 +00:00
Merge pull request #47 from TurtleP/TurtleP/stringx_max_split
[Enhancement]: add optional `max_split` to `stringx.split`
This commit is contained in:
commit
18347e0b72
15
stringx.lua
15
stringx.lua
@ -11,10 +11,17 @@ local stringx = setmetatable({}, {
|
|||||||
})
|
})
|
||||||
|
|
||||||
--split a string on a delimiter into an ordered table
|
--split a string on a delimiter into an ordered table
|
||||||
function stringx.split(self, delim)
|
function stringx.split(self, delim, limit)
|
||||||
delim = delim or ""
|
delim = delim or ""
|
||||||
|
limit = (limit ~= nil and limit) or math.huge
|
||||||
|
|
||||||
assert:type(self, "string", "stringx.split - self", 1)
|
assert:type(self, "string", "stringx.split - self", 1)
|
||||||
assert:type(delim, "string", "stringx.split - delim", 1)
|
assert:type(delim, "string", "stringx.split - delim", 1)
|
||||||
|
assert:type(limit, "number", "stringx.split - limit", 1)
|
||||||
|
|
||||||
|
if limit then
|
||||||
|
assert(limit >= 0, "max_split must be positive!")
|
||||||
|
end
|
||||||
|
|
||||||
--we try to create as little garbage as possible!
|
--we try to create as little garbage as possible!
|
||||||
--only one table to contain the result, plus the split strings.
|
--only one table to contain the result, plus the split strings.
|
||||||
@ -46,7 +53,11 @@ function stringx.split(self, delim)
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
if has_whole_delim then
|
if has_whole_delim then
|
||||||
table.insert(res, i)
|
if #res < limit then
|
||||||
|
table.insert(res, i)
|
||||||
|
else
|
||||||
|
break
|
||||||
|
end
|
||||||
end
|
end
|
||||||
--iterate forward
|
--iterate forward
|
||||||
i = i + delim_length
|
i = i + delim_length
|
||||||
|
Loading…
Reference in New Issue
Block a user