lua中逻辑运算符and与or的用法
2017-01-12 11:41
453 查看
总的来说就是,and返回导致返回值为false的那个值。a and b,如果a为假就返回a,否则返回b。 or的用法就是返回导致true的那个, a and b,如果a为真就返回a,否则返回B.
逻辑运算符认为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的语义,还返回了它的值.
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
true
true
true
不过正确的方案书写太过复杂,反而弄巧成拙。lua中没有提供语言内置的支持,还是转向正常的if/else吧。
当然,如果编码者能够断言c and a or b中的a一定为真,那直接用这种写法也不会错,但这就是一个hack了,不值得推崇。
逻辑运算符认为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的语义,还返回了它的值.
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
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) --truefalse
true
true
true
不过正确的方案书写太过复杂,反而弄巧成拙。lua中没有提供语言内置的支持,还是转向正常的if/else吧。
当然,如果编码者能够断言c and a or b中的a一定为真,那直接用这种写法也不会错,但这就是一个hack了,不值得推崇。
相关文章推荐
- Lua 协同程序coroutine 数据交换说明
- 腾讯XLua 01-lua来写MonoBehaviour
- Lua类的实现
- Lua学习笔记3. 函数可变参数和运算符、转义字符串、数组
- tolua 学习笔记 插件的使用
- lua 立即执行函数
- Lua 学习
- 腾讯开源手游热更新方案Xlua尝鲜(五)——xLua的配置
- Lua学习笔记之文件操作—io.open()、file:read()、require"nixio"
- 使用Lua的扩展库LuaSocket用例
- Lua学习笔记2. lua变量和 循环
- Lua学习笔记1,基本数据类型
- ngx_lua 模块API说明
- ubuntu/wireshark下Lua: Error during loading: [string "/usr/share/wireshark/init.lua"]:45
- 腾讯开源手游热更新方案Xlua尝鲜(四)——Lua调用C#
- 腾讯开源手游热更新方案Xlua尝鲜(三)——C#访问Lua
- Codeforces Round #383 (Div. 2) D. Arpa's weak amphitheater and Mehrdad's valuable Hoses 并查集+双重01背包
- LeetCode-399. Evaluate Division-思路详解-C++
- torch系列:关于luajit中string.format的支持
- lua面向对象