Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Kick Command breaking due to a nil value?

I have been recently coding a kick command (using a reference from the Devforum) but when I try kicking a player it breaks for attempting to index a nil value. I do not know exactly how to state my question for this except that it is not working. So I kind of expect this to be marked duplicate because it's probably been asked before, but I cannot find it.

Commands.kick = function(Sender, Arguments)
	local Message = table.concat(Arguments, " ")
	if (Arguments[1] == nil) then return end
	local userPlayer = tostring(Arguments[1]);
	local reason = tostring(Arguments[2]);
	if (Arguments[2] == nil) then
		reason = "No reason provided."
	end
	Players:FindFirstChild(userPlayer):Kick(reason)
end

The error is on line 24 (or line 9 for this snippet.)

ServerScriptService.Script:24: attempt to index a nil value

3 comments

0

then or either userPlayer is nil or reason is nil

0

Doesn't answer my question on how it's nil and how to solve it

0

Thanks for accepting

1 answer

✓ Accepted answer

The issue was that since you're using the admin tutorial here, it has this line in the "ParseMessage" function. What is does is that it uses string.lower to the message, causing the entire thing to become lowercase. Because of this, the kick command processed the usernames as lowercase therefore not finding any players.

local Commands = {}
local Prefix = "!"

local function ParseMessage(Player,Message)
	local PrefixMatch = string.match(Message,"^"..Prefix)
	
	if PrefixMatch then
		Message = string.gsub(Message,PrefixMatch,"",1)
		local Arguments = {}
		
		for Argument in string.gmatch(Message,"[^%s]+") do
			table.insert(Arguments,Argument)
			print(Argument)
		end
		
		local CommandName = Arguments[1]
		table.remove(Arguments,1)
		local CommandFunc = Commands[CommandName]
		
		if CommandFunc ~= nil then
			CommandFunc(Player,Arguments)
		end
	end
end

Commands.kick = function(Sender, Arguments)
    local Message = table.concat(Arguments, " ")
    if (Arguments[1] == nil) then return end
    local userPlayer = Arguments[

    local reason = Arguments[2];
    if (Arguments[2] == nil) then
        reason = "No reason provided."
    end
    local findPlayer = game:GetService("Players"):FindFirstChild(userPlayer)
    if findPlayer then
	  findPlayer:Kick(reason)
    else
	  warn("Player not found.")
    end
end

game.Players.PlayerAdded:Connect(function(plr)
	plr.Chatted:Connect(function(Message)
		ParseMessage(plr,Message)	
	end)
end)

I modified the code from the tutorial a little bit. Make sure to accept my answer if its right!

This discussion is preserved as it was. New answers, comments, and votes are closed.