Trying to get a random array not working

local RandomMood = User.Moods[math.random(1, #User.Moods)]

With User.Moods being

Moods = {
	Energy = 100,
	Happiness = 100,
	Hunger = 100,
	Hygiene = 100,
},

[ bad argument #2 to ‘random’ (interval is empty)]

Looking at it from my point of view, there’s no reason why this shouldn’t work

1 Like

You cannot get the length of a dictionary using #. The dictionary is also not indexed by number. You will need to iterate over the dictionary and build an array of values to pick randomly from. The method you’re picking a random mood from also won’t retain information about which mood.

1 Like

You are using a dictionary instead of an array for User.Moods, and dictionaries don’t have a length, or rather have a length of 0.

You might want to use either an actual array for your moods or a two-dimensional array, using the table returned as an interface, like here:

Moods = {
    {Name = "Energy", Value = 100},
    {Name = "Happiness", Value = 100},
    {Name = "Hunger", Value = 100},
    {Name = "Hygiene", Value = 100}
}
1 Like

Adding to what @qqtt991 Said, A simple solution to this would be

local elements = {}
for i,v in pairs(User.Moods) do
table.insert(elements,i)
end
local randomIndex = elements[math.random(1,#elements)]
local randomMood = User.Moods[randomIndex]

While @ObscureBrandon and @qqtt991 's solutions may work I’d highly suggest to follow up on @goldenstein64 idea of a 2 dimensional array.

This follows highly favorable design patterns and the accepted idea that the less control structures you have to use in your code the better. Here’s a solution using his idea.

Moods = {
    {Name = "Energy", Value = 100},
    {Name = "Happiness", Value = 100},
    {Name = "Hunger", Value = 100},
    {Name = "Hygiene", Value = 100}
}
local randomMood = Moods[math.random(1, #Moods)].Name
3 Likes