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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了