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

How do I use math.random On A Table?

Asked by 10 years ago

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

Log in to vote
1
Answered by
samfun123 235 Moderation Voter
10 years ago

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!

Ad

Answer this question