Problem with tables

I am trying to get a random number from a table using local key = math.random(1,#open) but have ran into an error:


I decided to print it using print(#open,open) and got
image

it’s saying there is no values but when I printed the table it shows otherwise, does anyone know why?

Thank you.

Could you show your whole code?

local function pickPlayers(Holder,Template,ServerSize)
	
	local players = players:GetPlayers()
	local spare = ServerSize-#players
	local open = {}
	
	for i = 1,ServerSize do
		local frame = Template:Clone()
		frame.Name = "frame"..i
		frame.Parent = Holder
		open[i] = i
	end
	
	local function loop()
		for i,player in pairs(players)do
			local key = math.random(1,#open)
			local value = open[key]
			
			setPlayerToFrame(player,Holder:FindFirstChild("frame"..value))
			
			open[key] = nil
			
			for i=1,#open do
				if open[i-1] == nil then
					open[i-1] = open[i]
					open[i] = nil
				end 
			end
		end
	end
	
	loop()
	
	if spare > 0 then
		repeat
			loop()
			spare -=#players
			print(#open,open) -- This is the line I printed on
		until
			spare <=0 
	end
end

You can’t use # (length operator) on dictionaries, that would only work on arrays.

local array = {
	1, 3, 5, 6, 8, 9, 10
}
local dictionary = {
	[0] = 5,
	[8] = 10,
	[15] = 17,
	[25] = 50
}

warn(#array) -- 7
warn(#dictionary) -- 0

So this error happens because you’re doing math.random(1, 0).

how would I find the amount of values in the dictionary?

1 Like

You would have to use a custom function, like this:

local function GetLength(table)
	local counter = 0 
	
	for _,v in pairs(table) do
		counter += 1
	end
	
	return counter
end

local array = {
	1, 3, 5, 6, 8, 9, 10
}
local dictionary = {
	[0] = 5,
	[8] = 10,
	[15] = 17,
	[25] = 50
}

local function GetLength(table) -- this works for both arrays and dictionaries
	local counter = 0 
	
	for _,v in pairs(table) do
		counter += 1
	end
	
	return counter
end

warn(#array) -- 7
warn(#dictionary) -- 0
warn(GetLength(dictionary)) -- 4
1 Like

Convert it into an array if you can (for better performance), if not use an incremental function like the one provided.