If not then statements and nil

I’m having a very hard time understanding why this code still runs.

local gloop = nil
if not gloop then
print("bruh how")
end

I have no idea how this code is able to run without any conditions!! like for example

if 1+2  == 3 then 
-- 1+2 = 3 is the condition.
end

I haven’t thought of ANY solutions for this so far! please help.

doing not is asking if it is either nil or false.

1 Like

It’s because it’s doing the opposite of nil which is true. not takes the falseness or truthiness of the statement and does the inverse

Truthy - doing not on it returns false:

  • strings
  • numbers (including 0)
  • tables
  • functions

Falsy - doing not on it returns true:

  • nil
  • false
print(not nil) --> true
print(not false) --> true
print(not '') --> false
print(not function() end) --> false

Edit:

You can also use these in if statements

if not nil then
    print('not nil')
end
if not function() end then
    print('will never print')
else
    print('will always print')
end

But keep in mind how Lua “reads” code

if not 1 == 1 then
-- is really
if (not 1) == 1
-- which is the same as
if false == 1
-- if you want to check if 1 ~= 1 you could use
if 1 ~= 1 then
-- or
if not (1 == 1)
2 Likes

well if you didn’t have the “not” there it would check if gloop exists
since gloop is nil “if gloop then” wouldn’t run, adding a “not” makes it run

1 Like

its because if statements only run when its condition its true or anything else that is not nil or false!

1 Like