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!
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.
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