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

How do I print a random value from a table?

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

✓ Accepted answer

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

4 comments

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.

0

You just need to set the random selection to nil like randomselection = nil

0

What do you mean? like Text.Text = Codes[math.random(nil, #Codes)] ?

0

No, You need to set the value of the variable to nil, such as thisvriablevalueis = nil

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