Is it Necessary to add a check for nil? Here is an example:
pie=workspace.Pie if pie ==nil then print("xP Pi") end
Do you **Have **to add it or do you add it whenever you want to?
Please Respect that I am a Beginner in need of knowledge
It depends on the situation. Typically, it isn't necessary; to quote the Lua reference manual (2.4.4):
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).
This means that if false then
is equivalent to if nil then
and if workspace:FindFirstChild("Pie") then
is equivalent to if true then
(assuming workspace.Pie exists; if you're not sure if it exists, you should use workspace:FindFirstChild("Pie") instead of workspace.Pie so that it returns nil in case it doesn't exist, instead of erroring).
As such, the following two pieces of code are equivalent, too:
pie = workspace:FindFirstChild("Pie") if pie == nil then ... end
pie = workspace:FindFirstChild("Pie") if not pie then ... end
Using not pie
would technically being equivalent to using the expression pie == nil or pie == false
, which comes down to the same thing as pie == nil
if FindFirstChild is used to get the value.
Imagine you want a function that prints the argument unless no argument was given. You could do this:
function foo(arg) if arg ~= nil then print(arg) end end
Converting the ~= nil
check would turn it into this:
function bar(arg) if arg then print(arg) end end
If you were to use foo("banana")
and bar("banana")
, they would both print "banana". If you used foo()
and bar()
, neither of them would print anything, as expected.
However, if you were to use foo(false)
and bar(false)
, then foo would print "false", while bar would print nothing.
Aside from this subtle difference, they come down to the same thing though.
First off, if the object was nil,
pie=workspace.Pie
^That would give you an error.
One way to obtain the condition of nil is by using the method FindFirstChild
.
What FindFirstChild
does is it returns the object that appears with the given name. If there is no object with that name, it returns nil.
So rather you can do:
pie=workspace:FindFirstChild("Pie") if pie ==nil then print("xP Pi") end