Help with string value being nil

Hey all, Scott here

So I’m trying to recreate an NPC chat system that was used in a legacy game I’m trying to recreate.

Currently, it does indeed work but every so often I get an error message in my output stating “20: attempt to index nil with 'Value”

Here is the troublesome code:

--// Values
local settings = script.Settings --// Folder
local lastUsed = script.lastUsed.Value --// ObjectValue
local cD = script.Parent.ClickDetector
local newText = nil --//Currently nil, turns into a ObjectValue
local color = script.Settings.textColor.Value --// StringValue
local cooldown = script.Settings.cooldownSeconds.Value --// IntValue
local textFolder = script.Settings.Text:GetChildren()


--//Speak Function
function speak()
	--// Repeats code until value "newText" isnt equal to the last used text.
	repeat
		wait()
		local newTextRand = textFolder[math.random(0,#textFolder)]
		newText = newTextRand
	until newText ~= lastUsed
	--// It then uses the chat function and plugs where the chat will be adorned to, the text, and the chat color.
	game.Chat:Chat(settings.whereToChat.Value,newText.Value,Enum.ChatColor[color]) --// Line of issue.
	--// It then sets "lastUsed" to "newText" and then clears it with nil.
	wait(cooldown)
	lastUsed = newText
	newText = nil
end



cD.MouseClick:Connect(speak)

I apologize if my code is messy or anything like that, I’m still trying to get back into programming.

I think the problem is at this line, where you’re getting a random number from [0, #textFolder]. Since lua arrays start at 1, if your random number happens to be 0 you will be indexing a nil index.

Replace the line above with this:

local newTextRand = textFolder[math.random(#textFolder)]
3 Likes

It’s textFolder[math.random(1,#textFolder)]

I see, thank you for the help!