Unable to assign property Text, string expected, got nil

This seems to be happening at random moments. I have made a script to make a message GUI generate random messages. The code is here.

while wait(5) do
	local gui = script.Parent

	local messages = {
		"msg1",  -- Replaced messages with example strings
		"msg2",
		"msg3",
		"msg4"
	}

	local rand = math.random(0, 3)
	
	gui.Message.Text = messages[rand]
end

As said previously, at somewhat random moments it seems to be returning the same error. Any help?

It doesn’t go down to 0 just do math.random(1,4) instead cause lua tables start at 1

3 Likes

try using :ToString on the table.

This is the correct answer, but to add on to it, you can use the # to get the length of the table, so if you change the table, then you don’t have to worry about changing the rest of the code:

while wait(5) do
	local gui = script.Parent

	local messages = {
		"msg1",  -- Replaced messages with example strings
		"msg2",
		"msg3",
		"msg4"
	}
	
	gui.Message.Text = messages[math.random(#messages)]
end
2 Likes

I also did what @paetemc2 suggested. I started programming in JS, so I’m still used to tables having 0 as the first index. Thank you.

1 Like

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