Output says nil, but it's not

It should be deleting the folder under PlayerAdds in ServerStorage, but it’s giving out a nil error:

Capture

And this is what the output shows:

errors

The function is called when the player removes using the PlayerRemoving event.
This is the bit of code that’s causing the trouble.

local playerAdds = game.ServerStorage.PlayerAdds:FindFirstChild(player.UserId)

Which is later removed:

playerAdds:Destroy()

playerAdds does not exist then. Have you tried printing the contents of PlayerAdds to the output beforehand?

print("Contents:")
for i, child in next, PlayerAdds:GetChildren() do
    print(i, child)
end
print()

Yes, after I make the variable I print it in a for loop:

for i,v in pairs(game.ServerStorage.PlayerAdds:GetChildren()) do
		if v ~= nil then print(v.Name) end
	end

Which prints: “-1”

Is the user’s userId -1 or is it being set in a different way? Also, does print(PlayerAdds[-1]) or print(PlayerAdds["-1"]) error?

Yes, the UserId is -1 since i’m testing it in a test server via studio. Not sure what you’re asking for the second question…

Do either of those functions throw errors if you do them after checking with the variable? It might also be a scoping issue where playerAdds just does not exist in the scope that you are using it in.

do
    local test = workspace
    print(test) --Workspace
end
print(test) --nil

The only time this error occurs is when I add those two lines of code, otherwise if I remove them, I get no errors.

If you expect an item to exist, and aren’t going to be handling the case in which it doesn’t you should be indexing using [] and not FindFirstChild.
Ex: game.ServerStorage.PlayerAdds[player.UserId]

What Wulfe is referring to also is, does the behavior change when you index using a string vs a number? When you index with player.UserId vs tostring(player.UserId) does it make a difference?

If not, you should check if there’s a race in your code where the object may exist just before you index for it, or a similar issue.

Even with using [] it still prints out an error nil. As far as the string vs UserId, I don’t believe this should be an issue as I also have another folder named with the players UserId which doesn’t throw any errors.

If it errors with [] then that means it does not exist there and you should try checking why that may be. Maybe it gets destroyed before you use FindFirstChild on it?

Right guys, sorry. I forgot to add playerAdds in the RemoveFolders parameter… Really sorry about that. Silly mistake.

It’s fine, it happens lol. I guess it was the scoping issue/mistake I suggested then

2 Likes