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

How would I make it choose randomly from a table?

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

✓ Accepted answer

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.

3 comments

0

Well, the brackets for a table indicate the position & return the data from that position, to be more technical. :P

0

I didn't really know how to explain that part :P Thanks for giving the correct function of it though!

0

Np. :)

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