Searching if a dictionary has a key

Hello again dev forum, I have tried to experiment with dictionaries for my music system but I can’t figure out how I can detect if the dictionary has a key or nil. My dictionary is laid out as PlayerName as the key and SongID as the value as shown. My output does not show any errors so I am stumped. I used another dev forum which said this:

if dictionary[key] then
      
end

My code:

local MPService = game:GetService("MarketplaceService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local Songs = {5458164461, 5890507466, 4509807932 ,2023642240 ,4545958144 ,5942435291}
local Queue = {
	["Seven"] = 6023401272
}
local Music  = workspace:WaitForChild("Music")
local SongName = Music.SongName
local RequestedBy = Music.RequestedBy
local MusicRequestRemote = ReplicatedStorage:WaitForChild("MusicRequest")

MusicRequestRemote.OnServerEvent:Connect(function(Player, SongID)
	Queue[Player.Name] = SongID
end)

while wait() do
	local PlayerName, SongID = next(Queue, nil)
	
	if not PlayerName then
		for i in ipairs(Songs) do
			Music.SoundId = "rbxassetid://"..Songs[i]
			Music:Play()
			local Success, SongName = pcall(function()
				return MPService:GetProductInfo(Songs[i], Enum.InfoType.Asset)
			end)
			local Name = Success and SongName or "Error loading song name."
			SongName.Value = Name
			RequestedBy.Value = "Server"
			wait()
			wait(Music.TimeLength+0.15)
		end
	elseif PlayerName then
		for i in ipairs(Queue) do
			Music.SoundId = "rbxassetid://"..SongID
			Music:Play()
			local Success, SongName = pcall(function()
				return MPService:GetProductInfo(Songs[i], Enum.InfoType.Asset)
			end)
			local PlayerName, SongID = next(Queue, nil)
			local Name = Success and SongName or "Error loading song name."
			SongName.Value = Name
			RequestedBy.Value = PlayerName
			wait()
			wait(Music.TimeLength+0.15)
		end
	end
end

Thank you in advance!

Use the # operator to check for how many elements the dictionary contains. If there are no elements, it will yield 0. However, this only works with arrays and thus we have to discard this idea.

The other idea, in the other hand, is using the functions:
next(), pairs() and ipairs().

Using next(dictionary) will either yield nothing or something. If there’s none, it will return nil. However, this will only be used in general cases where there is no key specified only.

2 Likes