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

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

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

1 comment

0

Can you clarify what you mean by using it for tables?

2 answers

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

2 comments

0

Can you iterate what i = x means? I've never truly undestood it.

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.

table[math.random(1,#table)] 

-- would randomly choose something from a table

1 comment

1

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

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