Know if the index exist?

Hello developers!
Im making a admin commands model but my problem is instead of checking if the index exists in the dictionary, it only checks the value of it. Here’s the code I’ve used:

for _, s in pairs(Settings.Roles) do
		for _, n in pairs(s.players) do
			if n == player.Name then
				if not Moderator[player.Name] == nil then
					Moderator[player.Name] = s.Rank
				end
			else
				if Moderator[player.Name] == nil then
					Moderator[player.Name] = 0
				end
			end
		end
	end

I’ve searched and what i saw:
Check if something exists - #11 by TheTurtleMaster_2 [:x:]
How to Check for a Specific Item in a Table? - #5 by un1ND3X [:x:]
Can i check if a dictionary has a key - #7 by Mixu_78 [:x:]

Scripts i tried:
if table.find(Moderator, player.Name) then
if Moderator[player.Name] then
if Moderator[player.Name] == nil then
if Moderator[player.Name] ~= nil then

Thank you so much for the help! I appreciate it!

if Moderator[player.Name] then
    ...
end

Should work. How does the main module work? / How do you add different people into the module?


that was the module script i placed. and i change my alt username to “UsernameHere” in the module script.

(The moderator dictionary is in the server script, not module script)

also,
the problem is, it worked actually, but it changes the value to 0. as you can see in the script

if Moderator[player.Name] == nil then
					Moderator[player.Name] = 0
				end

image

1 Like

Perhaps create a function like:

local function IsModerator(ToFind, Data)
    for _, v in pairs(Data) do
        if v == ToFind then
            return true
        end
    end
    return false
end

And that might work, you just need to set ToFind to the user’s name and Data to the Moderators array.

It might also be that you’re looping twice inside of the checking system with the same “_” in it, like shown:

for _, a in pairs(...) do -- Here
    for _, v in pairs(...) do -- And here.
        ...
    end
end

Although I have never done it before with the same parameter at the start of a for loop, so I do not know with the last one.

local function IsModerator()
		for _a, v in pairs(Settings.Roles) do
			for _b, s in pairs(v.players) do
				if s == player.Name then
					Moderator[player.Name] = s.Rank
				end 
			end
		end
		Moderator[player.Name] = 0
	end

Did i do it correctly? cause it said ServerScriptService.Script:21: attempt to compare number <= nil

return

in a loop will stop the loop, so

local function IsModerator()
		for _a, v in pairs(Settings.Roles) do
			for _b, s in pairs(v.players) do
				if s == player.Name then
					Moderator[player.Name] = s.Rank
				end 
			end
		end
		Moderator[player.Name] = 0
	end

won’t work because it is not returning anything and so the data will reset. Also in the players you have a number, which is never used.

1 Like