gpt4 book ai didi

printing - 为什么 print(print()) 在 Lua 中不像 print(type(2)) 那样工作?

转载 作者:行者123 更新时间:2023-12-01 10:29:22 26 4
gpt4 key购买 nike

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

最佳答案

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

您可以通过以下示例看到不同之处:

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

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

we know print() returns back nil and prints a space.

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

关于printing - 为什么 print(print()) 在 Lua 中不像 print(type(2)) 那样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44329298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com