How would i randomly pick one string out of all the strings in a table?

im trying to get a message from my table possibleMsgs to be picked randomly so that i can send that message if that makes sense but idk how to do it. ty!

local actor:Actor = script:GetActor()

local possibleMsgs = {
	"hello i am from the actor",
	"idk",
	"pls work",
	"lol",
	"jajaja"
}

actor:SendMessage("msg", possibleMsgs)
1 Like

Hello!

When you have a table of values such as strings, they are automatically given numerical keys starting from 1 and going up.

For example, your table would actually look like this:

local possibleMsgs = {
	[1] = "hello i am from the actor",
	[2] = "idk",
	[3] = "pls work",
	[4] = "lol",
	[5] = "jajaja"
}

This is important because we can take those numbered keys, put them through a random generator, and grab a random value from the table.

To do that, we need to generate a random number between 1 and the length of your table which will actually be the key we access from the table to get a random string.

local randomString = possibleMsgs[math.random(1,#randomString)]

This will return a random string from your table.
Hope this helps!

1 Like

Hiya bloxy,

i noticed that in the output earlier. that’s absolutely perfect mate, that’s exactly what i wanted. thanks so much for your help!!! :slight_smile:

1 Like

Glad to help! Let me know if there’s anything you’re confused about or if there’s something that needs clarifying.

1 Like

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