Why this simple Kick script is not working?

Hi Guys, so I was testing this simple Kick script but it turns out an error, why it even throws error, I don’t think I wrote something wrong.

local command = "/kick"
local players = game.Players:GetPlayers()
local result

function matchPlayer(str)
	for i=1, #players do
		if string.find(players[i].Name, str) then
				result = players[i]
		end
	end
	return result
end
game.Players.PlayerAdded:Connect(function(player)
	
	player.Chatted:Connect(function(msg)
		if string.find(msg, command) then
			print("Found")
			local plrName = msg:split(" ")[2]
			local player2 = matchPlayer(plrName)
			player2:Kick()
		end
	end)
end)

Error -
ServerScriptService.Script:22: attempt to index nil with ‘Kick’ - Server - Script:22

which means no player were found with that pattern.
for an example, there’s a player named “LigmaBalls”
if you used :match("ligmaballs"), it wont match because the cases aren’t the same

1 Like

I know why the error is happening, I want to know what’s wrong in my script.

do

local player2 = matchPlayer(plrName)
if (not player2) then return print("i didnt find any player with that keyword.") end
player2:Kick()
1 Like

I even tried checking, nothing really happened, but I’ll try this once again, let’s see what happens.

1 Like

Ok, so it doesn’t find any player…

image

What’s really wrong in my code though ?

what did you say in the chat


/kick RobloxMastersTeam1 (it’s the id I was using in Studio)

Your calling GetPlayers only once when the script is first run. Any player who joins after will not be added to your current player list. Try changing the matchplayer function to this:

function matchPlayer(str)
	for _, plr in ipairs(game.Players:GetPlayers()) do
		if string.find(plr.Name, str) then
			result = plr
		end
	end
	return result
end
1 Like

was gonna type this, but this absolutely works because it always get the new updated list of players.

1 Like

Maybe you’re right, I did that mistake once, I forgot about it, let me try.

As thought, that worked! Thanks for reminding me about that mistake I did in past!

1 Like

Thanks to you too for helping me!

1 Like

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