Lit*_*Guy 3 printing lua types
我和Lua搞乱了几天,我发现了一些让我三思而后行的事情.我还没有阅读参考手册Lua 5.3,因为它似乎很复杂,我很快就会检查它.
好吧在lua 5.3中,我们知道print()返回 nil并打印一个空格.
>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?
Run Code Online (Sandbox Code Playgroud)
从函数返回任何内容与返回不同nil.结果可能会让人感到困惑,因为大部分时间都没有返回任何类似于返回的解释nil,但在这种情况下print,它不会打印nil,因为没有返回任何内容.
您可以通过以下示例看到差异:
print(select('#', (function() return end)())) -- prints 0
print(select('#', (function() return nil end)())) -- prints 1
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,返回值的数量为0,但在第二种情况下,此数字为1,因此在打印时,它将nil按预期显示.
我们知道print()返回nil并打印一个空格.
这两个print()都不正确:不返回nil; 什么也没有回报.它也不会打印空格,但在打印完所有值后会添加换行符,因此您可能会在第一个示例中看到三行打印.