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 5 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
5 years ago
Edited 5 years ago

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

0
im not the asker, but thanks RobloxGameingStudios 145 — 4y
0
thx helped me a lot with a secret TrustedInstaIler 17 — 4y
0
where should the table be inserted? QuantumxGeneral 25 — 4y
0
This is very helpful. THUNDER_WOW 203 — 3y
Ad
Log in to vote
0
Answered by 5 years ago
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.

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

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