Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 8 years ago
Edited 8 years ago

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

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago
Edited 8 years ago

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."
0
This is more than I could ask. Thank you so much! OldPalHappy 1477 — 8y
Ad

Answer this question