Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

faster string.Explode and string.Replace #1166

Merged
merged 4 commits into from
Aug 23, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 24 additions & 21 deletions garrysmod/lua/includes/extensions/string.lua
Original file line number Diff line number Diff line change
Expand Up @@ -76,28 +76,27 @@ end
-----------------------------------------------------------]]
local totable = string.ToTable
local string_sub = string.sub
local string_gsub = string.gsub
local string_gmatch = string.gmatch
local string_find = string.find
local string_len = string.len
function string.Explode(separator, str, withpattern)
if (separator == "") then return totable( str ) end


if withpattern == nil then
withpattern = false
end

local ret = {}
local index,lastPosition = 1,1

-- Escape all magic characters in separator
if not withpattern then separator = separator:PatternSafe() end

-- Find the parts
for startPosition,endPosition in string_gmatch( str, "()" .. separator.."()" ) do
ret[index] = string_sub( str, lastPosition, startPosition-1)
index = index + 1

-- Keep track of the position
lastPosition = endPosition
local current_pos = 1

for i = 1, string_len(str) do
local start_pos, end_pos = string_find(str, separator, current_pos, not withpattern)
if not start_pos then break end
ret[i] = string_sub(str, current_pos, start_pos - 1)
current_pos = end_pos + 1
end
-- Add last part by using the position we stored
ret[index] = string_sub( str, lastPosition)

ret[#ret + 1] = string_sub(str, current_pos)

return ret
end

Expand Down Expand Up @@ -232,9 +231,13 @@ end


function string.Replace( str, tofind, toreplace )
tofind = tofind:PatternSafe()
toreplace = toreplace:gsub( "%%", "%%%1" )
return ( str:gsub( tofind, toreplace ) )
local tbl = string.Explode(tofind, str)

if tbl[1] then
return table.concat(tbl, toreplace)
end

return str
end

--[[---------------------------------------------------------
Expand Down