Running one function multiple times

So basically this is the script I got

game.Players.PlayerAdded:Connect(function(player)
	player.Chatted:Connect(function(msg)
		local split = msg:split("")
		for i, v in pairs(split) do
			if split[1] == "!" then
				print(msg)
			end
		end
	end)
end)

when I say “!Hello” then

it prints 6 times(changes everytime)

2 Likes

It prints 6 times because there are 6 letters when looping through.
What is your goal here? Please elaborate.

1 Like

I would look into using String Pattern Anchors for checking if the command prefix was used.

oh :man_facepalming:
yea I was using for i, v in pairs soo it printed 6 times

Sorry didnt see that

Why do you need to loop through? Just do splits[1], splits[2] etc.
Also, string.split returns an array, you should have been using ipairs rather than pairs.

1 Like

If you need to split a string into tokens separated by whitespace, you can do something like this:

local tokens = {}
for s in msg:gmatch("%S+") do
	table.insert(tokens, s)
end

If you need to get just the first character in a string you can do something like this:

if (msg:sub(1, 1) == "!") then
	print(msg)
end
1 Like