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

Help on tables?

Asked by 9 years ago

How would you randomly pick something form a table, then print it? I've got this down:

local codes = {"xYxx28","7882qR","99212x","ui1123","sOap12","1337qw","723OpQ"}
for i = 1,#codes do 
    print(codes[i]) 
end

So, it would randomly pick one code and print it.

2 answers

Log in to vote
1
Answered by 9 years ago

You would want to access one of the keys in the table by using math.random, and going from 1,#Table. This is if you want to choose one randomly from a table. You can look at the example below if you don't understand.

local Food = {"Apple", "Orange", "Pair"} --The Table

local YummyFood = Food[math.random(1,#Food)] --Choose one randomly
print("a/an "..YummyFood.." is my favorite food") --Prints the chosen food

If this helps or answers your question then mark this one as the answer!

Ad
Log in to vote
1
Answered by
Bman8765 270 Moderation Voter
9 years ago

You need something called math.randomthis will generate a random number. It does require some numbers to be added. For example: math.random(minnum, maxnum)

local randomnum = math.random(1, 4)
print(randomnum)
-- You'll get a random number from 1-4

So in your script you could do:

local codes = {"xYxx28","7882qR","99212x","ui1123","sOap12","1337qw","723OpQ"}
randomnum = math.random(1, #codes) -- A number between 1 and the number of values in the table
print(codes[randomnum])

Then you can use this randomnumber as a directory for the table value. Similar to finding items in a workspace using [] allows you to search through something inside this item with that value.

If this helped make sure to click accept answer and thumbs up for others, if you need more info just ask!

0
I a bit confused about math.random but thank for explaining it Bman here a Point. UserOnly20Characters 890 — 9y

Answer this question