Getting a random object in a table

Basically

I have a table that is simply

game.ReplicatedStorage.folder:GetChildren()

I just want to know how i can select randomly one of the items in the table.

(I know it’s using math.random but i don’t remember how)

Any help is appreciated, thanks!

local children = game.ReplicatedStorage.folder:GetChildren()
local child = children[math.random(1,#children)]

That’s it in a nutshell.

‘#’ allows you to get the length of a Lua table
‘[]’ around children is allows you to get a member of a table by indexing it. you could also do stuff like children.bean or children[“bean”] or children[#children] to get the last one.
remember tables start at value 1, so math.random(1,…) will index from the first value onwards.

For anybody else, if you want a properly random number without influencing other code which users math.random() then you can also check this page out: Random | Roblox Creator Documentation

  local randomobject = Random.new()
  local children = game.ReplicatedStorage.folder:GetChildren()
  local child = children[randomobject:NextInteger(1,#children)]

hApY CoDing!

4 Likes