lua-users home
lua-l archive

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


On Thursday 05 February 2004 00:01, Asko Kauppi wrote:
> Insteead of the regular "_,_, str= string.find( "  I'm considering
> using the following functions:
>
> 	-----
> 	-- Useful when needing just a single return value (i.e. from
> 'string.find()')
> 	--
> 	function first( ... ) return arg[1] end
> 	function second( ... ) return arg[2] end
> 	function third( ... ) return arg[3] end
>
> This makes the code easier to read, and is not so obscure as the
> built-in '( )' notation
> (that only extracts the first item anyhow).
>
> What do you normally do - are there better ways to achive this?

I've always written specialised wrappers for individual functions, e.g.

function findfirst(s,p,i)
	local _,_,r = string.find(s,p,i)
	return r
end

That's just because it minimises the number of parameters/returns I have to 
think about. Arguably it makes the code less readable than your approach, 
since the reader may have to refer to findfirst to see what it does, but 
probably already knows what string.find does. I would be inclined though to 
write those functions as:

function first(x) return x end
function second(_, x) return x end
function third(_, _, x) return x end

It's about 5 times faster than constructing and indexing arg.