Should I use 'if not' or '~='?

The title explains everything needed to know.

It depends on preference. They do the same thing really.

1 Like

I mean, I feel like the ~= is more efficient, but only slightly.

if not first has to check if the value is equal to the other value, then it inverts it.
~= checks if the value is not equal to the other one.

~= has less steps in calculation

2 Likes

not just flips a Boolean value, it’s far quicker than the ~= operator, which needs to compare its operands.

1 Like

You should be using ~= for conditional tests and if not for conditional loops.

Here’s an article on the DevHub that answers your question:

I used to do “if not”, but using ~= is a lot better and simple.

if not (conditional) is not equivalent to ~= value. Both false and nil are falsy values in Lua which makes not return true for both.

Take a dictionary whose keys you want to check exist or not:

local dictionary = {
	Apple = 1, -- truthy
	Banana = "fruit", -- truthy
	Carrot = false -- falsy
}

local function DictionaryHasKey(key)
	if not dictionary[key] then
		return false
	else
		return true
	end
end

print(DictionaryHasKey("Apple")) -- true
print(DictionaryHasKey("Banana")) -- true
print(DictionaryHasKey("Carrot")) -- false (!!)
print(DictionaryHasKey("Durian")) -- false

-- the proper way to check would be:
print(dictionary["Carrot"] ~= nil) -- true

The two are not always interchangeable. Pick whichever one suits your use case better.

5 Likes