LUA中的and与or
2017-08-01 15:10
671 查看
LUA中的and与or
2013-01-04 14:51 17117人阅读 评论(2) 收藏 举报分类:
Lua(44)
逻辑运算符认为false和nil是假(false),其他为真,0也是true.
and的优先级比or高
其它语言中的and表示两者都为真的时候,才返回为真,而只要有一个假,都返回假.lua虽不仅返回假的语义,还返回导致假的值.也就是说
a and b
在a为false的时候,返回a,否则返回b.
or的处理与之类似,
a or b
在a为true的时候,返回a,否则返回b.
总之,and与or返回的不仅有true/false的语义,还返回了它的值.
[cpp] view
plain copy
a = nil
b = 1
exp = 1 < 2 and a or b
print(exp == a) --fales
exp = 1 > 2 and a or b
print(exp == b) --true
exp = (1 < 2 and {a} or {b})[1]
print(exp == a) --true
exp = (1 > 2 and {a} or {b})[1]
print(exp == b) --true
false
true
true
true
不过正确的方案书写太过复杂,反而弄巧成拙。lua中没有提供语言内置的支持,还是转向正常的if/else吧。
当然,如果编码者能够断言c and a or b中的a一定为真,那直接用这种写法也不会错,但这就是一个hack了,不值得推崇。
顶
相关文章推荐
- Lua a and b or c
- LUA中的and与or
- LUA中的and与or
- lua and or not
- lua and or not 逻辑运算符
- 该怎样理解 Lua 逻辑运算符 and 和 or 的设计?
- 逻辑操作符---Lua: and,or,not 对比 C++:&&,||,!
- Lua中and和or的用法和记忆方法
- lua中逻辑运算符and与or的用法
- lua 中 and 与 or 连用 类似 c 语言中 ? : 操作符
- lua 逻辑运算 and, or, not【转】
- lua 之 and or not
- Lua中and、or的一些特殊用法
- LUA中的and与or
- Lua中and、or的一些特殊使用方法
- LUA中的and与or
- LUA中的and与or
- lua and or not 逻辑运算符
- Lua中and、or的一些特殊用法
- lua and or not 逻辑运算符