Getting random objects in a table

Just practicing tables, I want to know how to get a random letter in my table and print it but I have no idea how to do it. I have tried using math.random but is it the way I am using it?

letters = {“A”, “B”, “C”, “D”}

for i,v in pairs(letters) do

output – function: 0x9aa4a90b3615a214 (x4)
22:41:04.224 function: 0x9aa4a90b3615a214
22:41:04.225 function: 0x9aa4a90b3615a214
22:41:04.227 function: 0x9aa4a90b3615a214

local letters = {"A", "B"}

print(letters[math.random(1, #letters)])
1 Like

Thank you! I added on to the script, so that once it printed 4 random letters 4 times, it stops!

local letters = {“A”, “B”, “C”, “D”}
number = 0

while number < 4 do
print(letters[math.random(1, #letters)])
number = number + 1

if number >= 4 then
print(“Repeat off”)

That is great! Good luck with learning more about tables. If you want a quick explanation as for what I did works, I basically just index the place in line of a random number from 1 to the amount of items inside of the table. If you do print(letters[1]), it will say “A”. So what I am doing is indexing a random number from the amount of values there are in the table to print it. Hope this helps, good luck on your journey! :slightly_smiling_face:

That is some very useful information, thanks for the help

1 Like

Are you able to do it with dictionaries?

If the dictionary keys are number, I think yes, but if not a number then no. (All keys must be a number)