if-statementlua

What is the best way to check for a nil value in Lua?


I've started learning Lua and saw these two ways to check for nil:

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

if (stats ~= nil) then 
    -- do stuff
end
    
if (stats) then 
    -- do stuff
end

Are the two if statements equivalent? If so, is there any advantage to including the extra ~= nil part?


Solution

  • Statement "~= nil" works also if stats = false.

    You can read in docs:

    The condition expression of a control structure can return any value. Both false and nil are considered false. All values different from nil and false are considered true (in particular, the number 0 and the empty string are also true).