lua-users home
lua-l archive

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


How about the semantics of the following?

function multireturn(num)
     if num == 0
        return
     elseif num == 1
        return 1
     elseif num == 2
        return 1, 2
    end
end

function multiparam(...)
    print(select("#", ..))
end

multiparam(multireturn(0))

That would print 1, if an empty return is coerced to a nil return.

-John

On Jan 25, 2008, at 12:16 PM, Ken Smith wrote:

I ran into a bit of Lua behavior I'd like to discuss in the forum.
Consider this example.  (Tested under Lua 5.1.3 on Mac OS X.)

cat<<EOF>test.lua
function nothing()
end

local result = nothing()

print(tostring(result))

print(tostring(nothing()))
EOF

The first print yields, "nil", whereas the second one causes the
following error.

lua: test.lua:8: bad argument #1 to 'tostring' (value expected)
stack traceback:
	[C]: in function 'tostring'
	test.lua:8: in main chunk
	[C]: ?

The manual is clear that a function "without...a return
statement...returns with no results" (2.5.9).  But then the discussion
of nil mentions that it "usually represents the absence of a useful
value" (2.2).

My expectation was that a function with no return would return no
results in the form of a nil.  Granted there is a conundrum, if a
function returns nil, then it returns a result.

The way I see it, a function without a return returns no values which
introduces another, distinct nil concept into the Lua runtime.  There
is nil, which is a placeholder value meaning, "different from all
other values", then there is true nil as is generated by a function
with no return which is the true absence of any value.

Clearly, the workarounds are unobtrusive and numerous.  However, I
find this curious, so I'd like to hear a few more opinions on this
issue.  Should a function with no return statement return 'nil', or
nothing?  Are they different semantically?