Table Help (15 chars)

I’m trying to pick random song tables from a module table from a module script, and I’m getting an error I’m not sure how to fix.

Here’s the modulescript:

local Tracklist = {
   
    ['Song1'] = {
   	
   	Composer = ("Vexitory"),
   	Name = ("Sphere"),
   	ID = ("")
   },
   
   
}

return Tracklist

This is the script:

local Tracklist = require(game.ServerStorage.Tracklist)

local RandomTrack = math.random(1, #Tracklist)

local f = Tracklist[RandomTrack]

print(tostring(f))

Error:

  ServerScriptService.Script:3: invalid argument #2 to 'random' (interval is empty)
Stack Begin
Script 'ServerScriptService.Script', Line 3
Stack End

My goal here is to select a random song table out of the module and be able to access the table’s body so my script can have information on the random song it has picked. How can I fix this?

Tracklist is no longer an array but a dictionary. It’s now an ‘unordered collections of key-value’, So math.random has no index to work with. You’ll need something like this:

local Tracklist = {

{
    Name = "Song1";
    Composer= "Vexitory";
    Id= 0;
};
{
    Name = "Song2";
    Composer= "Vexitory2";
    Id= 1;
};

}

For each song, you’ll need to create an ‘object’.

How would I still be able to organize song data? I’d hate to have to just use string manipulation.

#Tracklist will be 0 unless you get __len to work for tables and return a custom value or something, since the # operator is relevant to numerically indexed tables only, not dictionaries or hashmaps, it’ll return 0 and not count indexes in their case.

You could try using arrays and simulate key value pairs

local t = { {song = "etc.", id = 1, music = 2} }
print(#t) --> 1
print(t[1].song) --> etc.

I would have preferred actual learning instead of spoonfeeding, but you definitely helped and it solved my issue. Thanks.

1 Like

It’s fine, I understood completely

1 Like