Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Conditionals without comparisons?

I've seen conditional statements without any comparison before, ones that don't use equal, less than, greater than, etc. signs. I'm not sure how this works. If somebody could explain this it would be really helpful to finally understand this.

Here is an example of what I am talking about:

game.Players.PlayerAdded:connect(function(player)
	if player then
		print("New Player")
	end
end)

2 answers

✓ Accepted answer

In Lua, there are only two false values; everything else is considered true. This means that if 5 then end wiill run, and if {} then end will run.

The two false values are false and nil.

2 comments

0

So it pretty much replaces if player.Backpack.Gun == true then? As an example...

0

Sort of. You can think of it as being replaced with "if player.Backpack.Gun~=nil and player.Backpack.Gun~=false then".

Assuming the variable player references a Player object...

if player then

is the same as

if player ~= nil then

Essentially, when an object is used as a condition in a conditional statement, it is treated like a "true" statement. Conversely, if the reference to the object no longer exists, then the reference will return nil. This is equivalent to a false statement.

Keep in mind that fundamentally, all conditional statements are either true statements or false statements; there's no "in-between".

4 comments

0

I'm afraid that's not correct. player=false if player~=nil then print("Hello!") end will print, but player=false if player then print("Hello!") end will not.

0

I was typing in the context of the question; sorry if you misunderstood.

0

There's a nice little edit button there. I'll change my vote to an upvote if you correct the error.

0

Woops; it appears I didn't save my previous edit on mobile. Thanks again for pointing that out.

This discussion is preserved as it was. New answers, comments, and votes are closed.