Lua中if not object与type(object)=="nil"两种检查方式的差异疑问
Lua中
if not object和type(object) == "nil"的差异 直接说核心区别:
if not object then检查的是object是否为假值,Lua里的假值只有nil和false两个。所以不管object是nil还是false,这个条件都会成立。type(object) == "nil"是严格检查object的类型是否为nil,只有当object真的是nil时才会触发,哪怕object是false,这个条件也不成立。
举个实际例子对比:
local obj1 = nil local obj2 = false -- 两个条件都会触发执行 if not obj1 then print("obj1 通过 not 检查") end if type(obj1) == "nil" then print("obj1 通过 type 检查") end -- 只有not检查会触发,type检查不会 if not obj2 then print("obj2 通过 not 检查") end if type(obj2) == "nil" then print("obj2 通过 type 检查") end -- 这行不会执行
你说的“当object类型为nil时,not object同样生效”完全正确,但反过来,当object是false时,not object会生效,而type(object) == "nil"不会——这就是两者最关键的差异。
内容的提问来源于stack exchange,提问作者Snoogens
相关产品推荐
相关产品推荐

