Why is the variable written this way?

I am doing a RPG game using Evercyan RPG kit(I need to thanks to this KIT) and I just saw something that I didn’t understand. I am intermediate at scripting and need help.

	local Level = pData and pData:FindFirstChild("Stats") and pData.Stats:FindFirstChild("Level")

The variable is getting the Level from the player, why is this written this way instead of just:

pData.Stats:FindFirstChild("Level")

Why the “And”??

5 Likes

It checks for errors and makes sure that the code doesn’t break if certain conditions aren’t met.

5 Likes

This prevents the script from erroring if an instance within the pData.Stats.Level path doesn’t exist. Most specifically if pData or Stats doesn’t exist it returns false, if Level doesn’t exist it returns nil and if it exists it returns the Level instance.

The only difference between it and the pData.Stats:FindFirstChild("Level") statement is that instead of erroring if pData and Stats doesn’t exist, it returns false.

Basically it’s a short version of this:

if pData then
	local Stats = pData:FindFirstChild("Stats")
	if Stats then
		local Level = Stats:FindFirstChild("Level")
		--code
	end
end
8 Likes

Thank you both! I will mark the last one as the solution because he explained better though! I got, so it means that if the Level doesn’t exist, it will just return false and the other ones will be considered.?

2 Likes

If the Level doesn’t exist it returns nil, which is expected from FindFirstChild. It only returns false if its ancestors don’t exist(pData and Stats) which basically prevents/ignores the attempt to index nil with "{name}" error.

3 Likes

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