Table.find() returning error if output is nil

I’m trying to make a custom admin system and need to search through a table to see if the command exists. The script works perfectly fine when the command exists but when it doesn’t it breaks and sends errors on the lines with table.find().

Here is the code:

local function searchCommands(cmd)
	--Check Commands
	for _, command in pairs(commands) do
		if table.find(command.Commands, cmd) then
			return command
		end
	end	
	--Check CustomCommands
	for _, command in pairs(customCommands) do
		if table.find(command.Commands, cmd) then			
			return command
		end
	end	
	return false
end

The table is a module script with entries formatted like this:

module.ExampleCommand = {	
	Prefix = settings.Prefix;
	Commands = {"example";"examplecommand"};
	Args = {"Example argument"};
	Description = "This is an example command.";
	Hidden = true;
	Fun = false;
	AdminLevel = 0;
	Function = function(plr,args)
		print("This is an example command!")
		print("This command was sent by "..plr.Name)
		print(args[1])
	end
}

could you send the exact error in the output?

This is the error:

ServerScriptService.StarstruckAdmin.Core.CoreScripts.CoreModule:53: invalid argument #1 to 'find' (table expected, got nil)

I figured that was it. The command table doesnt have a Commands key which results in that error. You could use short circuiting to prevent that by checking if the command table has the Commands key.

replace this:

if table.find(command.Commands, cmd) then

with this:

if command.Commands and table.find(command.Commands, cmd) then

That returns the same error as before.

did you replace it for both for loops? Also could i see the new error because Im pretty sure it should be different than the old one

Never mind, I forgot to remove a print() that I was testing with. Your solution worked. Thank you.

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