lua-users home
lua-l archive

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


On Sun, Jun 21, 2009 at 10:45 AM, bb<bblochl@arcor.de> wrote:
> In my head-picture the function math.sin() delivers a return value and
> function print() does that as well. So there is only exactly one result
> in any of the two cases. The one (math.sin(1) gives 0.841... (for the
> argument used in the example here) and the other (print("Hello")) should
> give Hello.

No, print() has no return values. You can tell how many return values
a function call gave by using the select('#') function. Note that you
cannot query how many return values a function has, as it can (if it
wants to) return a different number of values depending on the
arguments passed to it. The following example shows that print()
returns no values, math.sin() returns 1 value, loadstring() can return
2, etc. Note that string.find() can return a different number of
values depending on how many captures are in the pattern argument.

> =select('#', print("Hello"))
Hello
0
> =select('#', math.sin(3))
1
> =select('#', loadstring"?")
2
> =select('#', ("AB"):find("(.)(.)"))
4
> =select('#', ("AB"):find("((.)(.))"))
5
> =select('#', ("xxxx"):find("(.)(.)(.)(.)"))
6

The fact that print() returns no values is important in understanding
type(print()). Like in table constructors, where the final expression
does not have its return values adjusted to 1 result, the same is true
for lists of expressions in function calls. In the case of the call to
type(), print() is the last expression, and as print() returns no
values, type() receives no values. The following two things are
functionally equivalent:

> =type(print("Hello"))
Hello
stdin:1: bad argument #1 to 'type' (value expected)
stack traceback:
        [C]: in function 'type'
        stdin:1: in main chunk
        [C]: ?

> print("Hello")
Hello
> =type()
stdin:1: bad argument #1 to 'type' (value expected)
stack traceback:
        [C]: in function 'type'
        stdin:1: in main chunk
        [C]: ?

Note that you can force any expression to exactly one return value by
wrapping it in a pair of round brackets. Thus while print() returns no
values, (print()) returns one value (nil):

> =type((print("Hello")))
Hello
nil