Cannot select a random item in tables

Hey,
So I wanted to select a random index in a table but there is a little issue.

So here the script :

local TestTable = {
	["Item1"] = "yeah",
	["Item2"] = "nice",
	["Item3"] = "good",
}

local RandomItem = TestTable[math.random(1, #TestTable)]

And it print a error in the output :

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

I can’t understand the issue, like 6 months ago I could select a random index from a table with that but now it’s not working.

I tried looking for solutions but I didn’t find anything.

Any help will be appreciated!

I believe this is due to you not using an arrey table.

I believe this is new and I am not sure why this is happening but when you use # on a dictionary it returns 0. So maybe try to get the number of children by just looping through the table.

Keys do not count when using the # operator.

This works:

local TestTable = {
	["Item1"] = "yeah",
	["Item2"] = "nice",
	["Item3"] = "good",
}


function sum() 
	local items = 0 for _,_ in pairs(TestTable) do items += 1 end 
	return items 
end

local RandomItem = TestTable["Item"..tostring(math.random(1,sum()))]
print(RandomItem)

Sum is not required in this situation,

local TestTable = {
	["Item1"] = "yeah",
	["Item2"] = "nice",
	["Item3"] = "good",
}

local RandomItem = TestTable["Item"..tostring(math.random(1,#TestTable))]
print(RandomItem)

Edit: My bad, it is. # does not work. (Really dumb how you cant use # to determine the length of the table when using keys.)

2 Likes

Oh alright thanks, but like… 6 months ago I tried this and that’s actually worked, does it changed ?

1 Like

You probably used something like this:

local myTable = {"bla","bla bla bla","bla bla"}
print(#myTable) --output: 3

Thats the only way it will work with # (if i’m not forgetting an other way)

I didn’t, I’m sure that I used the key thing, in a module script btw. But maybe scripts changed, anyways, thanks for the help!

1 Like

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