What will happened if use `if x then foo() end` to detect x is nil in Lua

54 views Asked by At

I 'm not sure is it ok to use if x then foo() end to detect x is not nil in Lua.

There's so many detect like this in the project at hand, so I need a suggestion should I change them all or let them go.

Thanks.

1

There are 1 answers

0
Nicol Bolas On

An expression is considered false, for the purposes of any condition statement, on exactly two conditions: the expression is the boolean value false or the expression is nil.

So if x then foo() end will call foo if x is neither nil nor false. If you want to restrict it to nil only (and you usually don't), then use x ~= nil.