lua-users home
lua-l archive

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


It was thus said that the Great David Collier once stated:
> in C I can write:
> 
>   if ( passed = myFunction( x , y , &z ) )
>        && ( passed = mySecondFunction( z, &q ) )
>   
> which is preferable to
> 
>   passed = function(x, y, &z)
>   if ( passed )
>   {
>       passed = mySecondFunction( z, &q ) )
>   
> ---------------------------
> Now Lua allows me to return more than one value, so I can write
> 
>   passed, z = myFunction(x, y)
>   
> but is there any way in Lua I can write
> 
>   if passed, z = myFunction(x, y)
>   
> and set both passed and z, but then test 'passed' ??
> 
> It would allow me to do:
> 
>   if     ( passed, z = myFunction(x, y) )
>      and ( passed, q = mySecondFunction(z) )
>      and ( passed, result = myThirdFunction(q) )
> 
> which is a lot more comapct than what I'm writing at present.

  That presupposes the syntax checks the first return argument in the if
statement.  Using the function outside the if statement now becomes somewhat
awkward:

	passed,z = myFunction(x,y)
	passed,q = mySecondFunction(z)

  Yes, I know---one should always check the return code, but isn't that what
pcall() is for?  Simulating exceptions in Lua?

  I found myself returning errors last when writing C modules, for example:

	sock,err = net.socket('ip','udp')	-- [1]

so that both these segments would work for checking errors:

	sock1 = net.socket('ip','udp')
	if sock1 == nil then print("ERROR") end
	sock2,err = net.socket('ip','udp')
	if sock2 == nil then print("ERROR",err) end

I suppose with your proposal, I could still do:

	if  sock1,err1 = net.socket('ip','udp') ~= nil
	and sock2,err2 = net.socket('ip','udp') ~= nil
	then
	  ...
	end

which doesn't seem too bad to me.

  -spc (But I can live without it ... )

[1]	Yes, it duplicates features of luasocket, but ...

	1. I was learning how to write C extensions to Lua
	2. I wanted IPv6 support, which luasocket at the time didn't support
	3. I didn't need all the functionality of luasocket

	Code can be viewed here:
	https://github.com/spc476/lua-conmanorg/blob/master/src/net.c