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

How do I get a random choice from a table? [closed]

Asked by 6 years ago

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?

Locked by NotFrindow, Shounak123, ScuffedAI, NGC4637, and gskw

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

3 answers

Log in to vote
8
Answered by
yHasteeD 1819 Moderation Voter
6 years ago
Edited 6 years ago

You can use math.random

Examples:

1local table = {"Apple","Orange","String"} -- Items table.
2 
3local value = math.random(1,#table) -- Get random number with 1 to length of table.
4local picked_value = table[value] -- Pick value from table
5 
6print(tostring(picked_value)) -- Print picked value

Pick a random player

01local players = {} -- Table
02 
03-- Add players to table
04for i,v in pairs(game.Players:GetPlayers()) do
05    table.insert(players,v.Name) -- insert player names to table
06end
07 
08if players[1] ~= nil then -- Check if table is not nil.
09    -- Pick random player
10    local value = math.random(1,#players)
11    local picked = players[value]
12 
13    print("I got player " .. tostring(picked))
14else
15    print("Table nil")
16end

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 :)

0
im not the asker, but thanks RobloxGameingStudios 145 — 5y
0
thx helped me a lot with a secret TrustedInstaIler 17 — 5y
0
where should the table be inserted? QuantumxGeneral 25 — 5y
0
This is very helpful. THUNDER_WOW 203 — 4y
Ad
Log in to vote
0
Answered by 6 years ago
1local table = {string1, string2, string3} -- make a table
2local Chosen = math.Random(0, #table) -- random #
3 
4print(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.

0
In Lua array indices start at 1. tab[0] will be nil unless explicitly defined User#24403 69 — 6y
0
is math.random not math.Random and do not use 0,#table use 1,#table yHasteeD 1819 — 6y
Log in to vote
0
Answered by 4 years ago

yHasteeD also used this answer but whatever...

1local strings = {"hello", "hello2", "hello3"}
2local random_number = math.rando({1, #strings)
3local picked_string = strings[random_number]
4 
5print(picked_string)

you can also combine strings like this:

1print("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