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

How do I print a random value from a table?

Asked by 8 years ago

So I made a table, and I'm trying to select a random one and make that a text for a gui but I don't know how to select a random one from the table

Codes = {"Mickey", "Goofy", "Pete", "Sleeping beauty", "Snow White", "Donald Duck"}

Click.MouseButton1Click:connect(function()
    Text.Text = "Getting your code, wait a second"
    wait(1)
    Text.Text = (Codes[Codes:random()]) --error
end)

error: Workspace.KeyDoor.SurfaceGui.Frame.Script:12: attempt to call method 'random' (a nil value) any help?

1 answer

Log in to vote
2
Answered by 8 years ago

Use this

Codes = {"Mickey", "Goofy", "Pete", "Sleeping beauty", "Snow White", "Donald Duck"}

Click.MouseButton1Click:connect(function()
    Text.Text = "Getting your code, wait a second"
    wait(1)
    Text.Text = Codes[math.random(1, #Codes)] 
end)

Explanation Ok, so basically, Your Goal ~ you have a series of objects/children in a table and now you want to select a random value

Normally we use math.random(indexstart, indexend) to get a random value from a given limit aka parameters, this function is pre-defined by ROBLOX and uses a certain algorithm to select randomly.

And, We know that we can access the elements of a table like this tablename[index]

Coming to your problem, We want to get a random number between 1(Since we start our index in tables from 1) and the number of elements present in the table (i.e the final index)

so what we can do is

local tablename = {element1, element2, element3}
random_selection = tablename[math.random(1, #tablename)] -- Since #tablename will give us all the elements in a table

Welp, Hope that helps! Sorry if I explained something incorrectly, if so feel free to correct me!

~ Eat caiks

0
Thanks. Just another question, how would I remove the string it selected? (Yes, I know, table.remove) like how to detect which one it is. DeveloperSolo 370 — 8y
0
You just need to set the random selection to nil like randomselection = nil buoyantair 123 — 8y
0
What do you mean? like Text.Text = Codes[math.random(nil, #Codes)] ? DeveloperSolo 370 — 8y
0
No, You need to set the value of the variable to nil, such as thisvriablevalueis = nil buoyantair 123 — 8y
Ad

Answer this question