Taking Parts Of Strings

Hey Dev fourm!

So im making a chat system where im needing to re-write basicly all chat functions I have finished /team but now im on /w…

So I need to somehow take a username from the middle of a string like “/w bobgamer100 Hello my freind im here to let you know your so cool!”

or:

“/w roblox YOOO ITS ROBLOX!”

But im not sure how to get text between 2 spaces i just need to get the username and then also the text (and store them into a variable hopefully)

Thanks!

(Edit: Yes I know roblox is strict about there chat systems but I have filtered it multiple times in my script to be extra safe.)

You can use string.split(str, " ")

local message = "/w Roblox hello roblox"
local words = string.split(message, " ")
local cmd = words[1]

if cmd == "/w" then
    local player = words[2]
    player = game.Players:FindFirstChild(player)
    if player then
        local msg = ""
        for i=3, (string.len(words) - 2) do
            msg = msg.. " " ..words[i]
        end

        print("A whisper was made to", player.Name, "saying", msg)
    end
end

I think that will work?

1 Like
local words = str:split(" ")
local command = table.remove(words, 1)
local name = table.remove(words, 1)
local message = table.concat(words, " ")

You would probably have to write some more code to take care of users with spaces in their names (if you even care about that) and add checks to make sure “words” has enough elements in the array, so table.remove(words, 1) doesn’t error for example

Sounds to me like you are making a chat command. If so then I highly recommend reading about the In-Experience Text Chat | Roblox Creator Documentation.

Like @Orbular3 said, you can use string.split. Then, depending on the amount of arguments, you can concat the rest of the table returned. In a custom command module you can use:

local function Run(ChatService)
	local function createPart(speakerName, message, channelName)
		if message:lower():sub(1, 3) == "/w " then -- this is where you define the command name
			message = message:sub(4, message:len()) --remove the inital command
			
			local arguments = message:split(" ")
			
			local username = table.remove(arguments, 1)
			local privateMessage = table.concat(arguments, " ")
			
			-- other code
			
			return true
		end
		return false
	end
 
	ChatService:RegisterProcessCommandsFunction("createPart", createPart)
end
 
return Run

Darn, while typing this looks like @heII_ish beat me to the punch. Great minds think alike or something like that.

you could also do

if message:match("^/w ") then
1 Like