【问题标题】:Why print(print()) not work like print(type(2)) in Lua?为什么 print(print()) 不像 Lua 中的 print(type(2)) 那样工作?
【发布时间】:2017-06-03 02:49:37
【问题描述】:

我已经和 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?

【问题讨论】:

  • print 没有返回任何内容。所以print(print()) 等于print() print()

标签: printing types lua


【解决方案1】:

从函数中不返回任何内容与返回 nil 不同。结果可能会令人困惑,因为大多数时候不返回任何内容的解释类似于返回 nil,但在 print 的情况下,它不会打印 nil,因为没有返回任何内容。

您可以通过以下示例看到差异:

print(select('#', (function() return end)())) -- prints 0
print(select('#', (function() return nil end)())) -- prints 1

在第一种情况下,返回值的个数是 0,但在第二种情况下,这个数字是 1,所以在打印时,它会如您所愿地显示 nil

我们知道 print() 返回 nil 并打印一个空格。

这在两个方面都不正确:print() 不返回 nil;它什么也不返回。它也不会打印空格,但会在打印所有值后添加一个换行符,因此您可能会在第一个示例中看到打印了三行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多