L03-03. boolean类型

一 . boolean类型具有两个值:true和false

 

二. 在Lua条件表达式中哪些代表true和false

 

  1. 在Lua中,boolean值并非用于条件测试的唯一方式,任何值都可以表示条件

  2. Lua中,条件测试把false和nil视为假,将除了false和nil之外的所有其他值视为真(特别的是,在条件检测中Lua语言把0和空字符串也视为真

 

print(0 == false)     --> false

b = 0;
print(b == true)      --> false b不等于true

if 5  then
    print("5 is true")      --->5 is true
else
    print("5 is false")
end 

if(0 and b) then
    print("0 and b is true")  --> 0 and b is true
else
    print("0 and b id false")
end

if(nil) then
    print("nil is true")
else
    print("nil is false")  --> nil is false
end

 

 

三. 逻辑运算符

  1. Lua中逻辑运算符分为:  not and or

    ① and运算符的结果为:如果第一个操作数为false,则返回第一个操作数;否则返回第二个操作数

    ② or运算符的结果为:如果第一个操作数为true,则返回第一个操作数;否则返回第二个操作数

    ③ not运算符的结果为:返回操作数的相反值(true or flase)

--and or 的用法
print(4 and 5)           --> 5
print(nil and 13)        --> nil
print(false and 13)      --> false
print(4 or 5)            --> 4
print(false or 5)        --> 5
     10 or 20            --> 10
     10 or error()       --> 10
     nil or "a"          --> "a"
     nil and 10          --> nil
     false and error()   --> false
     false and nil       --> false
     false or nil        --> nil
     10 and 20           --> 20
     
     
--not的用法
print (not nil)     --true
print (not false)   --true
-- 注意, 0也是真
print (not 0)       --true
print (not not 1)   --true
print (not not nil) --false

  2. and or 的短路规则

四. 三目运算

--第一张方式:  前提是a不为false或者nil
x = a == b and a or b
print(x)

--第二种方式: (推荐方式)
x = (a == b and {a} or {b})[1]

--这两种公式等价
epos = (epos == -1 or not(epos)) and #t1 or epos
epos = epos ~= -1 and epos or #t

 

posted @ 2022-09-11 17:43  小书臣  阅读(40)  评论(0编辑  收藏  举报