Reputation: 49
I have been messing with Lua for a couple of days and I have figured out some things that made me think twice. I have not yet read the reference manual Lua 5.3 because it seems to complicated , I will soon check on it.
Ok in lua 5.3 , we know print() returns back nil and prints a space.
>print(print(print()))
--this prints three spaces
--but print() returns nil so print(nil) should
--print nil. But instead it is printing 3 spaces
>print(type(2))
number --this prints a number since type(2) returns a
--number , but this doesn't work with print(print())
--why?
Upvotes: 3
Views: 246
Reputation: 26784
Returning nothing from a function is not the same as returning nil
. The results may be confusing as most of the time returning nothing is interpreted similar to returning nil
, but in the case of print
, it doesn't print nil
, because nothing is returned.
You can see the difference with the following examples:
print(select('#', (function() return end)())) -- prints 0
print(select('#', (function() return nil end)())) -- prints 1
In the first case the number of returned values is 0, but in the second case this number is 1, so when printed, it will show nil
as you expect.
we know print() returns back nil and prints a space.
This is incorrect on both counts: print()
doesn't return nil
; it returns nothing. It also doesn't print a space, but it adds a newline after all its values are printed, so you probably see three lines printed in your first example.
Upvotes: 6