The roblox developer website is not good for tables. How can I create a table with a few string texts, then it chooses and prints a random string from the table?
How do I get a random choice from a table?
3 answers
You can use math.random
Examples:
local table = {"Apple","Orange","String"} -- Items table.
local value = math.random(1,#table) -- Get random number with 1 to length of table.
local picked_value = table[value] -- Pick value from table
print(tostring(picked_value)) -- Print picked value
Pick a random player
local players = {} -- Table
-- Add players to table
for i,v in pairs(game.Players:GetPlayers()) do
table.insert(players,v.Name) -- insert player names to table
end
if players[1] ~= nil then -- Check if table is not nil.
-- Pick random player
local value = math.random(1,#players)
local picked = players[value]
print("I got player " .. tostring(picked))
else
print("Table nil")
end
What does it do? takes a random number from 1 to the maximum length of the table.
Wiki pages:
Hope it helped :)
local table = {string1, string2, string3} -- make a table
local Chosen = math.Random(0, #table) -- random #
print(table[Chosen]) -- Print it
I apologize for the lack of typing. Im on my phone right now so its very hard. Please leave any questions in the comments.
2 comments
In Lua array indices start at 1. tab[0] will be nil unless explicitly defined
is math.random not math.Random and do not use 0,#table use 1,#table
yHasteeD also used this answer but whatever...
local strings = {"hello", "hello2", "hello3"}
local random_number = math.rando({1, #strings)
local picked_string = strings[random_number]
print(picked_string)
you can also combine strings like this:
print("The chosen string is "..picked_string.."!")
you can also change the variable names and what to print but I guess you already know that...
don't forget to type the previous variables otherwise Roblox won't know what picked_string is
This discussion is preserved as it was. New answers, comments, and votes are closed.

4 comments
im not the asker, but thanks
thx helped me a lot with a secret
where should the table be inserted?
This is very helpful.