lua-users home
lua-l archive

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

Hi all!

I know that it is possible to differentiate between a function returning no value and a function returning nil(s):

function f() return end
function g() return nil end

select('#',f()) --> 0
select('#',g()) --> 1

I'd like to know two things:

(1) is it safe to rely on such behaviour? I.e. is it intentional or is it only an implementation detail that may change at any time, even with minor releases of Lua? Lua 5.2 still complies, but haven't found a clear reference to this behaviour in the manual.

I only found:

"Results are returned using the return statement (see §2.4.4). If control reaches the end of a function without encountering a return statement, then the function returns with no results. "


"The return statement is used to return values from a function or a chunk (which is just a function). Functions and chunks can return more than one value, and so the syntax for the return statement is

	stat ::= return [explist]

But it is not clear that "return" with an empty explist is the same as returning with no return statement (currently it behaves that way, but can we rely on that?)

(2) assuming that (1) is intentional and stable, I'd like to pass a function (call it "func") to an higher order function that will call it many times and do different things according to whether func returned no values instead of only nil values.

How can I detect the number of returned values of "func" without calling it twice?

I only came up with this solution (here simplified), but it seems rather inefficient, since it forces an additional call to an helper function:

function higher( func )
  local nrets
  local function helper( ... )
    nrets = select( '#', ... )
    return ...

  local ret1, ret2 = helper( func() )
  if nrets == 0 then
    print "func returned no values"
    print "func returned something:"
    print( ret1, ret2 )

Is there a simpler idiom to avoid the call to "helper"?

Any hints or pointer appreciated!

-- Lorenzo