我在一个中看到了这段代码Lua 风格指南
print(x == "yes" and "YES!" or x)
Context:
local function test(x)
print(x == "yes" and "YES!" or x)
-- rather than if x == "yes" then print("YES!") else print(x) end
end
" x == "yes" 和 "YES!" 到底发生了什么?
为什么它打印“是!”或 (x) 不“真实”或 (x) ?
EDIT:
是不是像:
X == "yes" -- > true
true and (value) -- > value
print( (x == "yes") and value)
因此,检查 x 的值“yes”会得到 true,将 true 添加到某个值会得到该值,然后打印此过程会打印该值,对吧?
来自docs:
如果为 false,则运算符 and 返回其第一个参数;否则,它返回第二个参数。
所以,true and "YES!"
评估为"YES!"
.
这个方案之所以有效,是因为如果第一个参数为假,则整个表达式将变为假(与第一个参数相同);否则它将变得与第二个参数相同,当且仅当它为真将使整个表达式为真。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)