Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
-1

Conditionals without comparisons? [closed]

Asked by 10 years ago

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)

Locked by Articulating

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

2 answers

Log in to vote
2
Answered by 10 years ago

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.

0
So it pretty much replaces `if player.Backpack.Gun == true then`? As an example... FearMeIAmLag 1161 — 10y
0
Sort of. You can think of it as being replaced with "if player.Backpack.Gun~=nil and player.Backpack.Gun~=false then". TheLuaWeaver 301 — 10y
Ad
Log in to vote
0
Answered by
Unclear 1776 Moderation Voter
10 years ago

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".

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. TheLuaWeaver 301 — 10y
0
I was typing in the context of the question; sorry if you misunderstood. Unclear 1776 — 10y
0
There's a nice little edit button there. I'll change my vote to an upvote if you correct the error. TheLuaWeaver 301 — 10y
0
Woops; it appears I didn't save my previous edit on mobile. Thanks again for pointing that out. Unclear 1776 — 10y