lua-users home
lua-l archive

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


I had another idea.
If you want so badly to optimize this routine, it is probably because it
will be called often.
So you can do the following:

hardRange = "  1,  2"
hrUpperLimit = 2

function AddRange(newUpperLimit)
	if newUpperLimit > hrUpperLimit then
		local s = ''
		for i = hrUpperLimit+1, newUpperLimit do
			s = string.format("%s,%3s", s, i)
		end
		hardRange = hardRange .. s
		hrUpperLimit = newUpperLimit
	end
end

function numeric_range_tranformer5(s)
	ctor = function(from, to)
		local n1 = tonumber(from)
		local n2 = tonumber(to)
		if n1 >= n2 then return from end
		if n2 > hrUpperLimit then
			AddRange(n2)
		end
		local r1 = (n1 - 1) * 4 + 1
		local r2 = n2 * 4 - 1
		local range = string.sub(hardRange, r1, r2)
		return string.gsub(range, ' ', '')
	end
	return (string.gsub(s, "(%d+)-(%d+)", ctor))
end

print(numeric_range_tranformer5("1-10"), hardRange)
print(numeric_range_tranformer5("2-5"), hardRange)
print(numeric_range_tranformer5("7-20"), hardRange)

This has been hastily written and tested, beware of hidden bugs! I haven't
tested the performance, but it 
should be good.
You can initialize by calling a AddRange with a value than should fit 90% of
conversions...
And if your application doesn't mind spaces in the generated range, you can
drop the final gsub (or use 
zeroes instead of spaces), it would be faster.
Of course, you can also drop r1, r2 and range and inline them, that's just
the way I write code, finding it 
easier to read.

HTH.

-- 
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--
Philippe Lhoste (Paris -- France)
Professional programmer and amateur artist
http://jove.prohosting.com/~philho/
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--

+++ GMX - Mail, Messaging & more  http://www.gmx.net +++
Bitte lächeln! Fotogalerie online mit GMX ohne eigene Homepage!