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
Shawnyg 4330 Trusted Badge of Merit Snack Break Moderation Voter Community Moderator
9 years ago

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

Log in to vote
1
Answered by 9 years ago

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

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
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! Shawnyg 4330 — 9y
Ad
Log in to vote
0
Answered by 9 years ago

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!

0
Not quite. I'm when I meant a range, I meant a range within the table. Like, from "Apple" to "Green" Shawnyg 4330 — 9y
0
Well you can get the positions of the 2, and then put them in the table. Discern 1007 — 9y
0
Positions? What do you mean? Shawnyg 4330 — 9y
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! Shawnyg 4330 — 9y

Answer this question