How to detect if there is a space in your message?

Lets say your trying to do the command :pm (player) (message). How do I detect when there is a space in the message? Do I just have to continuously use pcalls whenever there is an error for each lettered username?

This code works


local Message = "This is a message"
local SpaceCounter = 0

for i = 1, #Message do
    if string.sub(Message, i, i) == " " then
        print("White space")

        SpaceCounter = SpaceCounter + 1

        if SpaceCounter == 1 then
            --code
        elseif SpaceCounter == 2 then
            --code
        end
    end
end

Output


White space
White space
White space

2 Likes

It might be useful to mention that all strings have the string library as methods.
So this:

local s = "Hello World!"
s = string.sub(s, 1, 5) --> Hello

Would be the same as this:

local s = "Hello World!"
s = s.sub(s, 1, 5) --> Hello

And therefore this:

local s = "Hello World!"
s = s:sub(1, 5) --> Hello

You can use string.match to simply find any whitespace character:

if Message:match("%s") then
    --whitespace found
end

However, you can use string.gsub to replace it with something else quickly:

--This would remove all whitespace from a string.
Message = Message:gsub("%s+", "")
8 Likes

Couldn’t you simply use string.find()

i.e

local function has_space(str)
return string.find(str," ")
end
8 Likes

Can you describe what you’re actually trying to do? Are you trying to extract parameters out of a chat string for a command? Simply detecting spaces sounds like an X Y problem.

You can use string.find and Lua string patterns to extract parameters from strings.

if string.sub(message, 1, 3) == ":pm" then
    local _, _, playerName, message = string.find(message, ":pm (%S+) (.+)")
    -- etc...
end
2 Likes

Just as a heads up, Roblox introduced their own string.split method to the string global, which you can use instead of matching

It takes a delimiter and returns an array of strings split by the delimiter
Example:

local message = ':pm Player1 Hello I am Player2'
local parameters = message:split(' ')
print(parameters) -- {':pm', 'Player1', 'Hello', 'I', 'am', 'Player2'}

local command = table.remove(parameters, 1) -- ':pm'
local playerName = table.remove(parameters, 1) -- 'Player1'
local privateMessage = table.concat(parameters, ' ') -- 'Hello I am Player2'
11 Likes

The art of making commands is normally handle with string manipulation. For this particular situation, I would do something like this

local function printWords(message)
    for word in message:gmatch("%S+") do
        print(word)
    end
end

printWords("Hello world!")

--Output:
--Hello
--World!

Gmatch basically iterates through each word in the message. You could use this to know what the player is asking for in the command.

3 Likes