Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I get a random choice from a table?

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?

3 answers

✓ Accepted answer

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:

For loop

math.random

Hope it helped :)

4 comments

0

im not the asker, but thanks

0

thx helped me a lot with a secret

0

where should the table be inserted?

0

This is very helpful.

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

0

In Lua array indices start at 1. tab[0] will be nil unless explicitly defined

0

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.