Faster string.split implementation.

This commit is contained in:
Diego Martinez 2014-12-18 23:50:31 -03:00 committed by kwolekr
parent 86cfbc21da
commit ab55da589c

@ -155,33 +155,33 @@ function dump(o, indent, nested, level)
end end
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
function string.split(str, delim, include_empty, max_splits) -- Localize functions to avoid table lookups (better performance).
local table_insert = table.insert
local str_sub, str_find = string.sub, string.find
function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
delim = delim or "," delim = delim or ","
max_splits = max_splits or 0 max_splits = max_splits or -1
local fields = {} local items = {}
local num_splits = 0 local pos, len, seplen = 1, #str, #delim
local last_pos = 0 local plain = not sep_is_pattern
for part, pos in str:gmatch("(.-)[" .. delim .. "]()") do max_splits = max_splits + 1
last_pos = pos repeat
if include_empty or part ~= "" then local np, npe = str_find(str, delim, pos, plain)
num_splits = num_splits + 1 np, npe = (np or (len+1)), (npe or (len+1))
fields[num_splits] = part if (not np) or (max_splits == 1) then
if max_splits > 0 and num_splits + 1 >= max_splits then np = len + 1
break npe = np
end
end end
end local s = str_sub(str, pos, np - 1)
-- Handle the last field if include_empty or (s ~= "") then
if max_splits <= 0 or num_splits <= max_splits then max_splits = max_splits - 1
local last_part = str:sub(last_pos) table_insert(items, s)
if include_empty or last_part ~= "" then
fields[num_splits + 1] = last_part
end end
end pos = npe + 1
return fields until (max_splits == 0) or (pos > len)
return items
end end
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
function file_exists(filename) function file_exists(filename)
local f = io.open(filename, "r") local f = io.open(filename, "r")