而在 Lua 中,它是如何处理的? [英] AND in Lua, how is it processed?

查看:19
本文介绍了而在 Lua 中,它是如何处理的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Lua 风格指南

print(x == "yes" and "YES!" or x)

上下文:

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!" 到底发生了什么?为什么打印YES!"或 (x) 不是真"或 (x) ?

What exactly happens at " x == "yes" and "YES!" ? Why does it print "YES!" or (x) not "true" or (x) ?

是不是这样:

X == "yes"               -- > true
true and (value)         -- > value
print( (x == "yes") and value)

所以检查 x 的值yes"的结果为 true,将 true 添加到值给出值并打印此过程打印值,对吗?

So checking x for the value "yes" results in true, adding true to a value gives the value and printing this process prints the value, right?

推荐答案

来自 docs:

运算符,如果为假则返回其第一个参数;否则,它返回它的第二个参数.

The operator and returns its first argument if it is false; otherwise, it returns its second argument.

因此,true 和 "YES!" 的计算结果为 "YES!".

Therefore, true and "YES!" evaluates to "YES!".

这个方案是有效的,因为如果第一个参数是假的,整个表达式就会变成假的(和第一个参数一样);否则它将与第二个参数相同,如果它为真,则整个表达式为真.

This scheme works because if the first argument is falsy, the whole expression will become falsy (the same as the first argument); otherwise it will become the same as the second argument, which iff that is truthy will make the whole expression truthy.

这篇关于而在 Lua 中,它是如何处理的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆