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))