lua --- 逻辑运算符小结

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

猜你喜欢

转载自www.cnblogs.com/luguoshuai/p/10051820.html
今日推荐