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

How would you use math.random() for a table?

Asked by 9 years ago

I know how to use it for random numbers, but what about tables?

0
Can you clarify what you mean by using it for tables? 1waffle1 2908 — 9y

2 answers

Log in to vote
3
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
9 years ago

If you have a table with numeric indices and want to get a random element from the table,

local t={"a","b","c","d","e","f","g"}
print(t[math.random(#t)])

writing math.random(#t) will produce a random number from 1 to the length of the table.

If what you mean is that you want to generate a table of random numbers, you can set the indices of a table to a random number:

local t={}
for i=1,10 do
    t[i]=math.random()
end
0
Can you iterate what i = x means? I've never truly undestood it. Meditate03 0 — 9y
0
It's a numeric for loop. It iterates from 1 to 10 in this case, calling the code inside of it again for each value of i. 1waffle1 2908 — 9y
Ad
Log in to vote
0
Answered by 9 years ago
table[math.random(1,#table)] 

-- would randomly choose something from a table

1
It would generate a random number between 1 and the number of elements in the table; it wouldn't cycle. 1waffle1 2908 — 9y

Answer this question