Choosing random value from a Module Script and accessing its info

Hi! I am trying to create a simple background music system.

I have a module script with songs:

local SongList = {
	
	["Closer"] = {
		ID = 7023459476,
		Creator = "Anthony Nikita"
	},
	
	["From Dust & Ashes"] = {
		ID = 7024254685,
		Creator = "Notaker"
	},	
}

return SongList

I have looked in heaps of different posts, but cannot figure this out.

How would I make the server script choose a RANDOM song from the module script, and then access the ID value and Creator value for that song?

3 Likes
local Songs = require(module path here)

local keys = {}
for key, _ in pairs(Songs) do table.insert(keys, key) end

local songName = keys[math.random(1, #keys)]
local songData = Songs[songName]

print(songName, songData)

This gives this error:

ServerScriptService.Script:6: invalid argument #2 to ‘random’ (interval is empty)

Can I ask, why do you have to do this part?

local keys = {}
for key, _ in pairs(Songs) do table.insert(keys, key) end

Are you not able to directly access the module script?

No, it’s because your table uses string keys to access its objects. SongList["Closer"] and such. In your case, you have to generate a random song and that can only be done by selecting a random number x from the total of y number of songs. So that part only makes it so your songs are numbered instead of accessed by their name. If you wanted to work directly with the module you’d have to change the SongList’s structure like such:

local SongList = {
	{
		Name = "From Dust & Ashes",
		ID = 7023459476,
		Creator = "Anthony Nikita"
	},
	
	{
		Name = "From Dust & Ashes",
		ID = 7024254685,
		Creator = "Notaker"
	},	
}

Perfect!
Thank you for the explanation!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.