lua-users home
lua-l archive

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


Rici Lake wrote:

On 27-Aug-05, at 10:05 AM, Adrian Sietsma wrote:

what about
a = (a<=b and a) or b


The goal of having a `min' operator would be to make the program *more* readable :)

i agree, but i still like Roberto's option of comparison operators returning the mathing object, instead of "true" - that matches and/or behaviour.

min = a<=b or b
min = b<a or a  -- also min
max = a > b or b

min3 = (a < b and a < c) or b < c or c
max3 = (a > b and a > c) or b > c or c

you can also tune the comparison for equality ordering.

some timing, for fun

> mymin=function(a,b) return ((a <= b) and a) or b end
> t0 = function(n) local t = os.timems() for i =1,2*n do local a = ((i<=n) and i) or n end return( os.timems() - t) end > t1 = function() local t = os.timems() for i =1,1e7 do mymin(i,5e6) end return( os.timems() - t) end > t2 = function(n) local t = os.timems() local min=mymin for i =1,n*2 do min(i,n) end return( os.timems() - t) end > t1 = function(n) local t = os.timems() for i =1,n*2 do mymin(i,n) end return( os.timems() - t) end > t3 = function(n) local t = os.timems() for i =1,2*n do local a = math.min(i,n) end return( os.timems() - t) end > t4 = function(n) local t = os.timems() local min=math.min for i =1,n*2 do min(i,n) end return( os.timems() - t) end
> print(t0(1e6),t1(1e6),t2(1e6),t3(1e6),t4(1e6))
150.21606445313 440.63403320313 420.60498046875 550.7919921875  410.59008789063
>

so - inline logic is fastest (of course); local copy of math.min next, then local min func, then math.min.


Adrian