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?
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