[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: split method?
- From: Wesley Smith <wesley.hoke@...>
- Date: Mon, 27 Jun 2011 11:06:16 -0700
> I’ve got it working, but I don’t understand it.
>
>
>
> function string:split(delimiter)
>
> local result = { }
>
> local from = 1
>
> local delim_from, delim_to = string.find( self, delimiter, from )
>
> while delim_from do
>
> table.insert( result, string.sub( self, from , delim_from-1 )
> )
>
> from = delim_to + 1
>
> delim_from, delim_to = string.find( self, delimiter, from )
>
> end
>
> table.insert( result, string.sub( self, from ) )
>
> return result
>
> end
>
>
>
> This is how I’m calling it:
>
>
>
> local myDateString = "2011-06-21"
>
> local myDateTbl = myDateString.split(myDateString,"-")
>
> dump_table(myDateTbl)
>
I think this function could be a lot simpler. string.gmatch is more
suited to this type of problem than string.find IMHO:
local myDateString = "2011-06-21"
function string:split(delim)
local res = {}
for v in self:gmatch(string.format("([^%s]+)%s?", delim, delim)) do
res[#res+1] = v
end
return res
end
local myDateTbl = myDateString.split(myDateString,"-")
print(unpack(myDateTbl))