Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How would I choose a string randomly out of a table?

Asked by 10 years ago

I need to know how to randomly show a string from a table on a TextLabel. Here's what I've got:

messages = {"Message1", "Message2", "Message3"}

script.Parent.Text = --?

What do I put where the '?' is?

Thanks in advance for your help!

2 answers

Log in to vote
1
Answered by
Redbullusa 1580 Moderation Voter
10 years ago

You can use the math.random() mathematical function.

messages = {"Message1", "Message2", "Message3"}

RandomMessage = math.random(1, #messages)

script.Parent.Text = messages[RandomMessage]

Regarding the RandomMessage variable, it is just a number. The math.random() function picks a number from 1 to the length of messages, or 3.

In line 6, the Text property will display one of the message in the nth place of the array given from the RandomMessage variable. This script is assuming that it is within any scope for it to function as intended.

Ad
Log in to vote
0
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
10 years ago

What you need to do is index the table using math.random

Because, when you index a table.. you use a number for the operator. If we use math.random, with a minimum of 1, and a maximum of the total number of indexes in the table then it will choose randomely from the table(:

Example;

local messages = {"Message1", "Message2", "Message3"}

local msg = messages[math.random(1,#messages)] --Get the random index

script.Parent.Text = msg --Set the text

0
ninja'd.. Goulstem 8144 — 10y

Answer this question