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.
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!
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."