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

How to pick a random value from a table?

Asked by
lucas4114 607 Moderation Voter
8 years ago

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

Log in to vote
0
Answered by
Mystdar 352 Moderation Voter
8 years ago

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
0
ooh i feel dumb now lucas4114 607 — 8y
0
Haha, no problem, that is what this site is for! Mystdar 352 — 8y
0
Making people feel dumb. iFlusters 355 — 8y
Ad

Answer this question