How can I get a player by only part of their name?

The title says it all, how can I get a player by a part of their name?
This is the function I have:

if args[2] then
		if args[2] == "me" then
			return {player}
		elseif args[2] == "all" then
			local players = {}
			for _,v in pairs (game.Players:GetPlayers()) do
				table.insert(players, v)
			end
			return players
		else
			--get player
		end
	end
	return {player}

You could get a list of every player name and search each one for the section of name you have. If only one player has that part in their name, that’s the player. You would have to handle the situation where multiple players have that part in their name.
Something like:

local found = {}
for _,v in pairs(game:GetService("Players"):GetPlayers()) do
    if string.find(v.Name, args[2])) then --I assumed args[2] would be the part of the name.
        table.insert(found, v)
    end
end

Also, instead of looping through all players and adding them to a new list and returning that, you can just use return game:GetService("Players"):GetPlayers().

I’d wan’t to get one player, so how could I implement that in my current code?

If you want to return a player object instead of a list you could change it to:

for _,v in pairs(game:GetService("Players"):GetPlayers()) do
    if string.find(v.Name, args[2])) then --I assumed args[2] would be the part of the name.
        return v
    end
end

If multiple players have the same part in their name, it will just select the first one it finds.

1 Like