Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I match a string with an object?

I tried this:

local plrs = game.Players:GetPlayers

function findPlayer(message,speaker)
	if (string.sub(message,1,5) == "kill/" and (string.sub(message,7) == plrs.Name then
		print("kaboom.")
end

This script is trying to match a chat message with an object, but this won't work.

BTW, don't tell me I don't know how to use tables and to add parenthesis, I just want to know how I am supposed to get a string and if the string matches with the player's name, then print kaboom.

1 answer

✓ Accepted answer

Well, there are several mistakes here.

One is, as you listed in your initial message, the lack of parenthesis in the part

local plrs = game.Players:GetPlayers

which won't work unless you make it

local plrs = game.Players:GetPlayers()

Next, in the statement plrs, you have a list of all the players in the game - Not one player. Take for example if I did

local plrs = game.Players:GetPlayers()

plrs might be a list like:

[1] - Player1

[2] - sayhisam1

[3] - laughablehaha

and so on. plrs.Name isn't actually a part of this list, so your script will throw an error at you because it doesn't know what to do because you are asking for something that doesn't exist.

To remedy this, you can check if the player's name matches for each and every player in the list. This is done with a loop, as follows:

for i,v in pairs(plrs) do
	if v.Name == string.sub(message,7) then
		print("Kaboom")
		break -- This stops the loop
	end
end

Putting it all together, you might end up with some code like this:

local plrs = game.Players:GetPlayers()

function findPlayer(message,speaker)
	 if (string.sub(message,1,5) == "kill/" then
		for i,v in pairs(plrs) do
			if v.Name == string.sub(message,7) then
				print("Kaboom")
				break -- This stops the loop
			end
		end
	end
end

There are also quite a few more errors here, such as the usage of string.sub() in order to find the player's name. It won't work because string.sub() returns a substring of a string, meaning that if you have something of variable length like a player's name, you won't necessarily know how long the substring should be.

1 comment

0

Thank you!!

This discussion is preserved as it was. New answers, comments, and votes are closed.