Attempt to index nil with "FindFirstChild"

This simple script is supposed to check if the object exists, if not, make it.

local recMessages
if not recMessagesApp:FindFirstChild(plr.UserId).Messages.ReceivedMessages then

	recMessages = createConvo(plr, toPlr)

else

	recMessages = recMessagesApp:FindFirstChild(plr.UserId).Messages.ReceivedMessages

end

Error:
ServerScriptService.PhoneHandlerServer:147: attempt to index nil with 'Messages'

Whats’s wrong?

this mean recMessagesApp.plr.Userid = nil

Oh alright. Maybe if should check if the user ID is nil?

local recMessages
if recMessagesApp:FindFirstChild(plr.UserId) then
if not recMessagesApp:FindFirstChild(plr.UserId).Messages.ReceivedMessages then

	recMessages = createConvo(plr, toPlr)

else

	recMessages = recMessagesApp:FindFirstChild(plr.UserId).Messages.ReceivedMessages
end
end

You need to research Defensive Programming.

The basic concept is remember that variables can be nullable (nil - they have no value).
Such as ‘recMessages’ - by your code that is null by default.
The function FindFirstChild can return a null value.

Hence, attempt to index nil with Messages - you need to write your code defensively
The player’s UserId isn’t null - there’s just no entry in recMessagesApp of plr’s UserId.

--these "local variable = this or that" lines mean, if "this" isn't nil - use this, otherwise use "that"

local playerRecMessages = recMessagesApp:FindFirstChild(plr.UserId)
local messages = playerRecMessages and playerRecMessages:FindFirstChild("Messages")
local received = messages and messages:FindFirstChild("ReceivedMessages")

local recMessages = received or createConvo(plr,toPlr) -- if received is nil, createConvo instead

-Edit- missread part of the script - edited the script to refelct.

@HedTB_Dev - I’m presuming here that “recMessagesApp”, “Messages” and “ReceivedMessages” are all folders or something - not tables?

2 Likes

UserId will never be null if its grabbed from the Player object.

@MdoxxxDSQa

1 Like

we dont know what inside playerRecMessages so yea

player.Userid never be nil but playerRecMessages(player.Userid) maybe nil

No, this is all a GUI. It’s frames. I could show you how the explorer looks if needed.

It looks like ReceivedMessages is the nil, and it couldn’t find it under Messages. You are better off making something like this, maybe?

--these "local variable = this or that" lines mean, if "this" isn't nil - use this, otherwise use "that"

local playerRecMessages = recMessagesApp:FindFirstChild(plr.UserId)
local messages = playerRecMessages and playerRecMessages:FindFirstChild("Messages")
local received = messages and messages:WaitForChild("ReceivedMessages") -- changed to wait?

local recMessages = received or createConvo(plr,toPlr) -- if received is nil, createConvo instead

However, I may be completely wrong and misreading this entire thread.