Posted 26 March 2012 - 03:12 PM
Does anyone have a working string split function? 'cause i'm not able doing one myself and i can't find one working on the web.
first one i used:
problem: throw an error if the string doesn't have at least 1 delimiter -> i stopped using it
second one i used:
problem: was working good, but then i had a problem with this test-script:
problem showed by this script: sep2 is splitted bad…
first one i used:
Spoiler
function separate(string, divider)
local function find(string, match, startIndex)
if not match then return nil end
_ = startIndex or 1
local _s = nil
local _e = nil
_len = match:len()
while true do
_t = string:sub( _ , _len + _ - 1)
if _t == match then
_s = _
_e = _ + _len - 1
break
end
_ = _ + 1
if _ > string:len() then break end
end
if _s == nil then return nil else return _s, _e end
end
if not divider then return nil end
local start = {}
local endS = {}
local n=1
repeat
if n==1 then
start[n], endS[n] = find(string, divider)
else
start[n], endS[n] = find(string, divider, endS[n-1]+1)
end
n=n+1
until start[n-1]==nil
local subs = {}
for n=1, #start+1 do
if n==1 then
subs[n] = string:sub(1, start[n]-1)
elseif n==#start+1 then
subs[n] = string:sub(endS[n-1]+1)
else
subs[n] = string:sub(endS[n-1]+1, start[n]-1)
end
end
return subs
end
second one i used:
Spoiler
function split(string, delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( string, delimiter, from )
while delim_from do
table.insert( result, string.sub( string, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( string, delimiter, from )
end
table.insert( result, string.sub( string, from ) )
return result
end
Spoiler
str2 = "0.1 1.2|0.3.test3 1.5.test5"
sep = split(str2, "|")
print("\nSEP 1: "..sep[1])
print("SEP 2: "..sep[2].."\n")
spl1 = split(sep[1], " ")
spl2 = split(sep[2], " ")
print("original: "..str2.."\nsplitted sep 1:")
for x, y in pairs(spl1) do
print(x.." "..y)
end
print("splitted sep 2:")
for x,y in pairs(spl2) do
print(x.." "..y)
end