lua-users home
lua-l archive

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


Under the hood, functions return and take a "vararg" (...) of values.
This vararg can be empty ("none"). A vararg of length 1 one containing
one nil value is different from a vararg of length 0. In one case, a
value is provided, in the other, no values are provided. They can be
distinguished using 'select("#", ...) == 0' if your function is variadic
(has ... as its parameter list). For a single nil value, 'select("#",
...)' will be 1. For no value, it will be 0.

The default return value is "none"/"nothing" - a vararg of length 0 -
rather than "nil" - a vararg of length 1.

When calling a function, the last expression in the argument list is
allowed to be variadic. If you instead want to treat it as a single
value, you can wrap it in parentheses, forcing it to be a single expression:

'tostring((b()))' will always truncate the vararg returned by 'b()' to a
single value. If 'b()' returns a vararg of length 0, '(b())' will be
nil. 'select(1, b())' would also work.

Explicitly assigning to a variable as you suggest is more readable though.

On 09.02.23 16:42, bil til wrote:
tostring(b())
stdin:1: bad argument #1 to 'tostring' (value expected)
You can write tostring( b() or nil), or var=b(); tostring(var), or I
think also use select(#,b()) - which then should give 0 possibly (but
I did not try myself).

... there are quite many nice applications of the fact, that nil and
"none" are different. (C function lua_type also returns LUA_TNONE
(different from LUA_TNIL), and you can easily get the stack count by
lua_gettop... but the type() function I think would NOT return 'none',
presumably type(b(0)) might return 'nil' you have to try...).