Why is this grabbing all the players?


Situation

I’m attempting to add players who have a similar amount of letters such as in my display name, J2T… if they have that in their first three letters, they get added to a table.

The issue is that when I do this command, everyone gets added and I have no idea why.

Workarounds;
None, as I have no idea what I did wrong.

Script

local argument = "chatmessage"
local argumentSplit = string.split(argument," ")[1] or argument
local args = string.split(argumentSplit,",")
for ind,arg in pairs (args) do
local playersFound = {}
for ind,arg in pairs (args) do
	for num,Player in pairs (Players:GetChildren()) do
		local PlayerUserame,PlayerDisplayName = string.lower(Player.Name),string.lower(Player.DisplayName)
		if string.sub(PlayerUserame,1,#arg) or string.sub(PlayerDisplayName,1,#arg) then
			table.insert(playersFound,Player.Name)
		end
	end
end

Thank you for any help you may give.

Personally, I would do something like this:

local CommandName = "chatmessage"
local StringStart = "J2T"

game.Players.PlayerAdded:Connect(function(player)
	player.Chatted:Connect(function(msg)
		local PlayersFound = {}
		if string.lower(msg) == string.lower(CommandName) then
			for _, player in pairs(game:GetService("Players"):GetPlayers()) do
				if string.sub(player.DisplayName, 1, string.len(StringStart)) == StringStart or string.sub(player.Name, 1, string.len(StringStart)) == StringStart then
					table.insert(PlayersFound, player.Name)
				end
			end
		end
	end)
end)
1 Like

Not sure what you are doing with the argument splitting, but I think the piece you are missing is in the if statement you need to check that the sub string is the one you are looking for

if "j2t" == string.sub(...) or "j2t" == string.sub(...)
if string.find(PlayerUsername, "^J2T") then

Just make use of the “string.find()” function, ^ is a regular expression pattern which matches the start of any string value.