Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why print(print()) not work like print(type(2)) in Lua?

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?
like image 764
Gourav Das Avatar asked Mar 19 '26 20:03

Gourav Das


1 Answers

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.

like image 197
Paul Kulchenko Avatar answered Mar 22 '26 17:03

Paul Kulchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!