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

How to pick a random value from a table?

The title may be a bit broad. Not just any random value, but, within a certain range. Like, from [2] to [5].

Question1 = {"What is the best pie?","Apple","Blue","Red","Green"}
print(Question1[math.random(#Question1)]) -- a little help here?

2 answers

To choose a random element from a specific range just change the numbers in the math.random function.

Question1 = {"What is the best pie?","Apple","Blue","Red","Green"}
print(Question1[math.random(FirstIndex,LastIndex)]) --Change FirstIndex and LastIndex

Alternatively you could write a function

function Random(tab,x,y)
return tab[math.random(x,y)]
end

Random({"Hi","Nope","Yes"},2,3) --return random value between index 2 and 3

1 comment

0

Thank you both! From both of your answers, I was able to comprehend what you were explaining. I didn't accept an answer since that would be unfair, so +1!

Your script is correct, now, to make it go from a certain range, it's just like doing math.random(1,5), let me show you;

Question1 = {"What is the best pie?","Apple","Blue","Red","Green"} --Heres your original table
print(Question1[math.random(2,#Question1)]) --This will choose one string randomly from the table [between 2-Number in Table 'Question1' [in this case, 'Apple' to 'Green']]; look closely, and there is a '2'! :D

Hope this helped!

4 comments

0

Not quite. I'm when I meant a range, I meant a range within the table. Like, from "Apple" to "Green"

0

Well you can get the positions of the 2, and then put them in the table.

0

Positions? What do you mean?

0

Thank you both! From both of your answers, I was able to comprehend what you were explaining. I didn't accept an answer since that would be unfair, so +1!

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