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

Don't know how to make my table randomly chosen How do I code this right?

Asked by 10 years ago

I've been working on a thing to randomly pick a image and well.. I know some people have done that with tables or I think they have.. I tried..

Table = {"Link","Link","Link"} -- Table was made.
while true do - Loop to refresh the script.
    if script.Parent.Parent.Visible == true then -- script is in a ImageLabel the parent to that is a frame.
        if script.Parent.Image == "" then --  Script is in an ImageLabel. Makes sure this doesn't overwrite the current image. 
            script.Parent.Image = "" .. Table{} -- How would I make this randomly pick a "Link" from my table? I tried this. Table{#} 
        end
    end
end

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

Lua provides a single neat way to do things randomly. That is the

math.random( low, high ) -- inclusive

function. It generates a random number between (and including) low and high.


So how can we generate values from a table if we can only make numbers?

We randomly pick which value we use by assigning them each a number. Specifically, we assign the 1st element 1, the 2nd element 2, etc.

Lua, of course, does this for us:

list = {5, 9, 2}
print(list[1], list[2], list[3])
--  5   9   2

So, to generate a random element from the above list, it would be sufficient to generate a random number 1 to 3:

print(list[ math.random(1, 3) ])
-- 5
-- 9
-- 2
-- (randomly)

Maybe we don't know ahead of time how many things are in list. Then we just plug in the length of list, which we denote by #list:

print( list[ math.random( 1, #list ) ] )

In your case, we have a list of URLs, so the use of this will look something like

gui.Image = assets[ math.random( 1, #assets ) ]

Remember to use good variable names! Table is a meaningless name that does not inform us why you made it or what it might be. Good code will read almost like English!

0
Explained perfectly and 100% understandable. Thank you for your answer. legoguy939 418 — 10y
Ad

Answer this question