You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 09:46:39