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

How would I make it choose randomly from a table?

Asked by 7 years ago

This is what I've done so far, I have a table called music and what I'm trying to do is choose a value from the table and have it chosen randomly and that ID from the table would be then replace the soundID that's currently there. How would I do this?

music = {"639026725","329574631","604164309",}




while wait(.5) do 
    script.Sound.SoundId = "rbxassetid://"..#music.math.random(1,3)
    script.Sound:Play()
    wait(5)
end


1 answer

Log in to vote
1
Answered by 7 years ago

The length operator you are using returns the length of a table, as stated here: http://wiki.roblox.com/index.php?title=Operator#Miscellaneous

You're doing the right thing, you've just forgotten about indexing, which can be used to grab something using square brackets. Here's the fixed version!

Oh, and you accidentally included a comma at your last id in the table.

music = {
    "639026725",
    "329574631",
    "604164309"
} --This type of layout of an array is optional, I just like it because it looks clean

while wait(0.5) do 
    script.Sound.SoundId = "rbxassetid://" .. music[math.random(1, #music)]
    script.Sound:Play()
    wait(5)
end

Note how I used '#music' instead of '3'. I did this so that you don't need to keep updating how many ids are in the table since the length operator returns the length of an array.

0
Well, the brackets for a table indicate the position & return the data from that position, to be more technical. :P TheeDeathCaster 2368 — 7y
0
I didn't really know how to explain that part :P Thanks for giving the correct function of it though! UltimateRaheem 75 — 7y
0
Np. :) TheeDeathCaster 2368 — 7y
Ad

Answer this question