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

Is there an easier way to get the message after the space in a string?

As in example, I have a script which detects when players speak, or chat. I want to get their message, but only after the space.

Example:

local message = "Hello dude."-- dude.

local message = "/kill all"-- all

local message = "I hate hate."-- hate hate.
I don't want the space included.

This is what I'm doing currently,

> = string.sub(message, string.find(message, "%s"), #message)

That works, but I feel like it could be simplified.

Thank you!

1 answer

✓ Accepted answer

First, if you use string methods your code becomes a little shorter and nicer. You can also use -1 to mean "end of string" so you don't have to say #message:

message:sub( message:find("%s"), -1)

But instead, you can use match. You describe a pattern and put () around the pieces you care about.

For example, you can capture everything from the beginning until the first space(s), then everything after the first space(s):

-- ^: start of the string 
-- (%S+) one or more non-space characters
-- %s+ one or more space characters
-- (.+) one or more characters
-- $: end of string
local before, after = message:match("^(%S+)%s+(.+)$")

Note that before and after will be nil if the message isn't the right form.

This would break the example into

  • "Hello dude." --> "Hello" and "dude."
  • "/kill all" --> "/kill" "all"
  • "I hate hate." --> "I" "hate hate."

1 comment

0

This is more than I could ask. Thank you so much!

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