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

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

问题描述

我在 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 =="是"和是!"的确切含义是什么? 为什么打印是!"或(x)不是"true"或(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的值为是"会得出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?

推荐答案

来自文档:

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

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

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

该方案之所以有效,是因为如果第一个参数为falsy,则整个表达式将为falsy(与第一个参数相同);否则它将与第二个参数相同,如果它是真实的,则将使整个表达式真实.

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中,AND是如何处理的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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