c语言中and和or的用法区别,Lua中and和or的用法和记忆方法

本文通过对比和C语言的&&,||,提供了一种更易记忆的方法来理解Lua中的and和or逻辑运算符。重点在于理解何时表达式值不依赖于第一个操作数,从而帮助读者快速准确地运用这些运算符。通过实例演示,展示了运算符行为并提供了代码截图作为参考。
摘要由CSDN通过智能技术生成

Lua中and 和 or是逻辑运算符,对他们的操作数而言false和nil为false,其他均为true

Lua官方手册中and 和 or的解释:

The conjunction operatorandreturns its first argument if this value isfalseornil; otherwise,andreturns its second argument.

如果第一个参数为false的话,and返回第一个参数,否则返回第二个参数

The disjunction operatororreturns its first argument if this value is different fromnilandfalse; otherwise,orreturns its second argument

如果第一个参数为true的话,or返回第一个参数,否则返回第二个参数

按照官方这种解释来记这两个运算符太恶心了,对于基础语法要有高标准掌握程度,这样读写代码才快速准确:

1.瞬间算出结果

2.相隔较长时间不会忘记混淆

按照官方这种记法恶心死你,根本达不到效果,我按照以下的方式记忆:

和C语音的&&,||相比,Lua的and or使用结果一样:即a && b等价于a and b,a || b等价于a or b.

来看Lua的a and b:如果a 为 true,表达式的值取决于b; a or b:如果a为false,表达式的值取决于b

a and b和a or b的本质区别是当a在什么情况下,表达式的值不需要考虑a, 只取决于b, 这两个运算符应该是从这个角度来设计的;

因此在记忆时,应该想到"a为何值时,只取决于b"这个模板.方式如下:

a and b:a为true时,返回b,否则返回a.

a or b:a为false时,返回b,否则返回a.

另外C语言的三目运算符a ? b : c等价于Lua中的a and b or c

最后上个输出截图:

print("----------------------------------------")

print("true and true = " .. tostring(true and true))

print("true and false = " .. tostring(true and false))

print("false and true = " .. tostring(false and true))

print("false and false = " .. tostring(false and false))

print("----------------------------------------")

print("true or true = " .. tostring(true or true))

print("true or false = " .. tostring(true or false))

print("false or true = " .. tostring(false or true))

print("false or false = " .. tostring(false or false))

print("----------------------------------------")

print("true and false or true = " .. tostring(true and 1 or 2))

print("false and false or true = " .. tostring(false and 1 or 2))

435a445ed42dbf2f4af01b7166708e6c.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值