lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Whoops. My original post fails if there are dashes (hyphens) in the 
line to be split. Here's a version that seems to work every single 
time:

function splitt(line, pattern)
	local rtrn={}
	while true do
		local front = string.gsub(line, pattern .. ".*", "")
		table.insert(rtrn, front)
		line = string.gsub(line, "^.-" .. pattern , "")
		if not string.find(line, pattern) then break end
	end
	table.insert(rtrn, (string.gsub(line, "%s*$", "")))
	return rtrn
end

SteveT


On Friday, July 15, 2011 09:45:37 PM Steve Litt wrote:
> Here's my implementation of a split function that turns a string
> into an array, splitting on a pattern like this:
> 
> local mytable = splitt(myline, mypattern)
> 
> Here's the code:
> 
> function splitt(line, pattern)
> 	local rtrn={}
> 	while true do
> 		local front = string.gsub(line, pattern .. ".*", "", 1)
> 		table.insert(rtrn, front)
> 		line = string.gsub(line, front .. pattern, "", 1)
> 		if not string.find(line, pattern) then break end
> 	end
> 	table.insert(rtrn, (string.gsub(line, "%s*$", "")))
> 	return rtrn
> end
> 
> I haven't incorporated Perl's ability to tell the maximum number of
> elements in the returning array, but that wouldn't be at all
> difficult.
> 
> Thanks
> 
> STeveT
> 
> Steve Litt
> Author: The Key to Everyday Excellence
> http://www.troubleshooters.com/bookstore/key_excellence.htm
> Twitter: http://www.twitter.com/stevelitt

-- 
Steve Litt
Author: The Key to Everyday Excellence
http://www.troubleshooters.com/bookstore/key_excellence.htm
Twitter: http://www.twitter.com/stevelitt