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

How do I use math.random On A Table?

Right, let's say I was making a loading screen, and I had a few subtitles to put under my game title. I want to select a random one to use. My script is:

_G.Print(script.Parent.Loading, "LOADING CERTIA", .07)
Subs = {"Reading thermonuclear reactor...", "Building weapons...", "Debugging...", "Manufacturing vehicles...", "Testing targeting matrix..."} 
wait(1)
local NOT = 0 --NOT stands for number of times. I want 5 of the above to print on to the TextLabel.
repeat
    wait(3)
    script.Parent.Loading.Loading2.Text = nil
    _G.Print(script.Parent.Loading.Loading2, Subs[math.random(1,5)], 0.07)
    NOT = NOT + 1
until NOT == 5

Now, I want to pick a random string out of the array Subs to use for printing at line 10. It all goes well until I try to use math.random(1,5). Even my global print function is working. What's the deal there?

1 answer

The best way to get a random place in a table is doing the following:

table[math.random(1,#table)]

This would return a random value from the table.

In your case you would replace table with Subs:

Subs[math.random(1,#Subs)]

In your code:

_G.Print(script.Parent.Loading, "LOADING CERTIA", .07)
Subs = {"Reading thermonuclear reactor...", "Building weapons...", "Debugging...", "Manufacturing vehicles...", "Testing targeting matrix..."} 
wait(1)
local NOT = 0 --NOT stands for number of times. I want 5 of the above to print on to the TextLabel.
repeat
    wait(3)
    script.Parent.Loading.Loading2.Text = nil
    _G.Print(script.Parent.Loading.Loading2, Subs[math.random(1,#Subs)], 0.07)
    NOT = NOT + 1
until NOT == 5

If you have any questions, concerns or just need some help with this PM me on ROBLOX!

This discussion is preserved as it was. New answers, comments, and votes are closed.