Command does not detect letters out of a string, only full strings

Hello. I am trying to make custom commands to my game, but, it only works if I type the full name of a player, not a few letters of it. Here is my code:

print("Welcome to Debate!đź’¬")

local players = game:GetService("Players");

local whitelist = {
	"XDvvvDX";
}

function player_Added(player)
	local isFound = false;
	
	for _, v in ipairs(whitelist) do
		if player.Name == v then
			isFound = true
		end
	end
	
	if not isFound then return end;
	
	local function chatted(message, recipent)	
		
		if recipent then return end;
		
		local splittedMessage = string.split(message, " ");
		
		if string.lower(splittedMessage[1]) == ":kick" then
			for _, v in ipairs(players:GetChildren()) do
				if string.find(splittedMessage[2], string.lower(v.Name)) then
					v:Kick("You have been kicked")
				end
			end
		end
	end;
	
	player.Chatted:Connect(chatted)
end;

players.PlayerAdded:Connect(player_Added)

“:kick xd” Doesn’t work
“:kick xdvvvdx” Works

You’re looking for the string "xdvvvdx" inside the string "xd".
Flip it around.

if string.find(splittedMessage[2], string.lower(v.Name)) then
if string.find(string.lower(v.Name), splittedMessage[2]) then -- to this

To accomplish this, you would use the string.sub function. sub stands for substring. Here’s a little explanation by Roblox about this function:

Returns the substring of s that starts at i and continues until j ; i and j may be negative. If j is absent, then it is assumed to be equal to the length of s . In particular, the call string.sub(s,1,j) returns s until as many characters as j , and string.sub(s, -i) returns a suffix of s with length i ."

Here’s a little function to find the player that you can incorporate into your code:

local function FindPlayer(chars)
    local Msg = chars:lower()
    for _, v in pairs(game.Players:GetPlayers()) do
        if Msg == v.Name:lower():sub(1, #Msg) then
            return v
        end
    end
end
1 Like

Thank you it is much appreciated! :pray:

No problem.
Note that splittedMessage[2] might not be lowercase. If you try to :kick XD, then nothing will happen, because it is looking for XD in xdvvvdx. Add a string.lower to that as well.

I would suggest making a separate function for finding an online player based on a string, so you don’t have to lowercase everything every time.

		if string.lower(splittedMessage[1]) == ":kick" then
			for _,target in pairs(matchPlayers(splittedMessage[2])) do
				target:Kick("You have been kicked")
			end
		end
local function matchPlayers(search)
	local matches = {}
	for _, v in ipairs(players:GetPlayers()) do -- do not use Players:GetChildren() to get all the players
		if string.find(string.lower(v.Name), string.lower(splittedMessage[2])) then
			table.insert(matches, v)
		end
	end
	return matches
end
1 Like