码迷,mamicode.com
首页 > 其他好文 > 详细

lua --- 逻辑运算符小结

时间:2018-12-02 00:32:59      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:class   实现   end   int   初始   not   code   一个   color   

lua中的逻辑运算符,认为只有false、nil为假,其他的都为真(包括0、空串)

a and b     -- 如果a为false,则返回a,否则返回b
a or b     -- 如果a为true,则返回a,否则返回b

1 print(4 and 5)           --5
2 print(nil and 12)        --nil
3 print(false and 13)      --false
4 print(4 or 5)            --4
5 print(false or 5)        --5

 

一个很实用的技巧:如果x为false或者nil则给x赋初始值v

x = x or v

等价于

if not x then
    x = v
end

 

C语言中的三元运算符

a ? b : c

在Lua中可以这样实现:

(a and b) or c

lua --- 逻辑运算符小结

标签:class   实现   end   int   初始   not   code   一个   color   

原文地址:https://www.cnblogs.com/luguoshuai/p/10051820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!