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

How to pick a random value from a table?

I've seen other people doing this so I know it's possible, what I do to pick random values is some thing like this:

local items = {item1, item2, item3}
local random = math.random(1,3)
local item = nil
if random == 1 then
	item = items[1]
end
if random == 2 then
	item = items[2]
end
if random == 3 then
	item = items[3]
end

But it takes a long time to do is there any better way I can get a random value from a table?

1 answer

✓ Accepted answer

Just set the "item" to be a random element of the array:

local items = {"item1", "item2", "item3"} -- You probably want them to be strings or the table is {nil, nil, nil}
item = items[math.random(1,3)]

And to test:

while true do
	local items = {"item1", "item2", "item3"}
	item = items[math.random(1,3)]
	print (item)
	wait(5)
end

3 comments

0

ooh i feel dumb now

0

Haha, no problem, that is what this site is for!

0

Making people feel dumb.

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