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 use string.sub?

I haven't worked with strings in a while, and I'm trying to take the first 3 letters of a message that a player says.

I already have the function set up and everything. What is wrong with this?

game.Players.LocalPlayer.Chatted:connect(message)
	if message.string.sub(1,3) == "abc" then
--code
end)
--Also, obviously don't worry about the LocalPlayer stuff, I have it set up with an actual playeradded event in the script. I just need help with line 2.

1 answer

✓ Accepted answer

There are two ways to use string.sub:

string.sub(String, Beginning, End)

String:sub(Beginning, End)

Both these ways work fine. To use it in your script, you can do it like this:

game.Players.LocalPlayer.Chatted:connect(message)
	if message:sub(1,3) == "abc" then
		--code
	end
end)

Or like this:

game.Players.LocalPlayer.Chatted:connect(message)
	if string.sub(message,1,3) == "abc" then
		--code
	end
end)

NOTE: if you type "ABC", the if will return false because "ABC" is not the same as "abc". In order to detect uppercased messages, you'll have to make the string all lowercase, by using the string.lower(String) function

EDIT: I answered your comment

game.Players.LocalPlayer.Chatted:connect(message)
	local Msg = string.lower(message) --This makes the message all lowercase
	local P1 = string.find(Msg, "(") --This returns the first occurance of "(" in "Msg"
	local P2 = string.find(Msg, ")") --This returns the first occurance of ")" in "Msg"
	if P1 and P2 then --If both parenthesis are there...
		local InMsg = string.sub(Msg, P1 + 1, P2 - 1) --This gets the text between the two parenthesis
		if InMsg == "abc" then --If the message between the parenthesis is whatever...
			--code
		end
	end
end)

Hope this helped!

NOTE: For more info on string manipulation, click here: String Manipulation

3 comments

0

Thanks!

0

Oh, also, one more question, how could I use strings to exclude certain characters? I want to excluded "msg", "(", and ")", and then only accept the things inside of it. I am currently using a string.sub to use all characters 5 and up, but that would include the parentheses at the end of the message. How could I get around this?

0

I answered your comment in my question

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