Snoogens
Snoogens

Reputation: 3

Lua nonsense to find if something is nil

There seems to be a difference between these two checks:

if not object then

if type(object) == "nil" then

However I really don't understand the difference. if type is "nil", shouldn't a not object then also work?

Upvotes: 0

Views: 237

Answers (1)

Lucas S.
Lucas S.

Reputation: 2401

Lua, like many other dynamically typed languages, has the concept of "truthy" and "falsy", where boolean expressions can handle more values than just actual booleans.

Each non-boolean value has a specific meaning attached when used in a boolean expression. Specifically:

  • nil and false are "falsy"
  • everything else is "truthy"

That is why (not nil) == (not false), but type(nil) ~= type(false), because not x is a boolean expression that coerces x to truthy/falsy, while type() checks the actual type.

Upvotes: 1

Related Questions