空值检查,最佳方法?

我正在学习lua,并看到这两种检查空值的方法

local stats = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)

if (stats ~= nil) then
    -- 做某些事情
end

if (stats) then
    -- 做某些事情
end

这两个if语句等效吗?如果是,包含额外的"~= nil"部分有什么优势吗?

点赞
用户7746452
用户7746452

你可以在 文档 中阅读到:

控制结构的条件表达式可以返回任何值。false 和 nil 都被视为 false。除了 nil 和 false 之外的所有值都被视为 true(特别地,数值 0 和空字符串也是 true)。"~= nil" 这个语句也适用于 stats = false

2020-02-20 08:02:39