-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_ext.lua
40 lines (35 loc) · 1.01 KB
/
string_ext.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
--[[
string_ext.lua
January 17th, 2013
]]
-- Split a string
--
-- Given a string and delimiter, split the string.
-- When given "a,,," returns a table { 'a', '', '', '' }
-- Parameters:
-- s The string to split. Note that instead of string.split(s, sep), you
-- can use s:split(sep).
-- sep The separator, a Lua pattern string. In the same spirit as
-- string.gmatch, if this is '', a table of 1+#s empty strings will be
-- returned.
-- Return values:
-- A table of the strings between separator matches.
function string.split(s,sep)
pat = '(.-)(' .. sep .. ')'
local t = {}
local n = 1
for p, q in s:gmatch(pat) do
-- There is weird behaviour from gmatch given an empty separator
-- pattern. To quote from the docs:
-- "As a special case, the empty capture () captures the current
-- string position (a number)."
if type(q) == 'number' then q = '' end
t[#t+1] = p
n = n + #p + #q
end
if sep ~= '' then
t[#t+1] = s:sub(n)
end
return t
end
return string