Table variable issue

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    A random chat for NPCs.
  2. What is the issue? Include screenshots / videos if possible!
    The chats aren’t random, they repeat.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    Changing code, yes.
    After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!
local t={"build","alone","together","live","team","rock","coming","hi","hello","die"}
local t2=t[math.random(1,#t)].." "..t[math.random(1,#t)].." "..t[math.random(1,#t)].." "..t[math.random(1,#t)]

Expected: build together team live, rock coming team live…
Actual: build together team live, build together team live, build together team live…

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

Are you by any chance setting the randomseed anywhere? If not, please show us a bigger scope of the code.

This is the entire script.

local chat=game:GetService("Chat")
local t={"build","alone","together","live","team","rock","coming","hi","hello","die"}
local t2=t[math.random(1,#t)].." "..t[math.random(1,#t)].." "..t[math.random(1,#t)].." "..t[math.random(1,#t)]
while true do
	chat:Chat(script.Parent.Head,t2,Enum.ChatColor.White)
	task.wait(math.random(0.5,2.5))
end

When you create the variable t2 it runs math.random() once each time to give you the index for the table and you concatenate them all into a single string. t2 is no longer a line of code but a fixed string.

To create a different string each time you need to use a function something like this should work:

local chat=game:GetService("Chat")
local t={"build","alone","together","live","team","rock","coming","hi","hello","die"}
local function randomText()
    return t[math.random(1,#t)].." "..t[math.random(1,#t)].." "..t[math.random(1,#t)].." "..t[math.random(1,#t)]
end
while true do
	chat:Chat(script.Parent.Head,randomText(),Enum.ChatColor.White)
	task.wait(math.random(0.5,2.5))
end

It works! Thank you so much! (char)

1 Like