Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Kick Command breaking due to a nil value?

Asked by 4 years ago

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

0
then or either userPlayer is nil or reason is nil EternalScythe 222 — 4y
0
Doesn't answer my question on *how* it's nil and how to solve it Warriorfoox 25 — 4y
0
Thanks for accepting Mr_Unlucky 1085 — 4y

1 answer

Log in to vote
0
Answered by
Mr_Unlucky 1085 Moderation Voter
4 years ago
Edited 4 years ago

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!

Ad

Answer this question