Assigning a variable with a player that doesn't exist

Hi, I’ll explain the issue here:

-- Say I have a variable that could contain a player

local T1Player1 = player

-- Then I try to access this players leaderstats

local T1Player1InitialKills = T1Player1:FindFirstChild("leaderstats").Kills.Value

-- If T1Player1 is actually = nil would this line above break the code? Or since I added findfirstchild would it just skip over it if T1Player1 is nil?

Thanks for any help (I know I could just add an if statement to check if T1Player1 is nil, but I have to do this for 6 players so i’m just trying to shorten the code so it doesn’t look as messy)

1 Like

If it was nil then it wouldn’t have the :FindFirstChild() method, and lua will return the error “Attempt to index nil with FindFirstChild”

2 Likes

Is there any other way of doing this in a single line? Basically I want to check a players leaderstat, but that player could be = nil

Adding on, if you wanted to shorten the code and only check whether the initial kills variable existed, you could do:

local T1Player1InitialKills = T1Player1 and T1Player1:FindFirstChild("leaderstats").Kills.Value
3 Likes

Thank you both very much :slight_smile:

gfdgdfgdf

1 Like

Sorry just a quick question. If the player is = nil, then what will the variable T1Player1InitialKills get assigned to?

Either false or nil (probably nil), which both equal false if used as a condition.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.