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

How to slice a string into multiple parts?

So I'm making customizable admin commands for players to take and edit but I want to make sure that their own custom made commands should work the way they should work.

The problem is I need to identify certain words in a string and cut them apart. It should look like something like this:

local Command = "/kick everyone"

function slice()
	-- do function stuff
	return "kick", "everyone"	
end

function process(command, Player)
	local cmd, quantity = slice(command)
	if quantity = "everyone" then
		return game.Players:GetPlayers()
	elseif quantity = "self" then
		return Player
	elseif quantity = "others" then
		local  PlayersTable = {}
		for i,v in pairs(game.Players:GetPlayers()) do
			if v ~= Player then
				table.insert(PlayersTable, v)
			end
		end
	end
end


I never really spent time learning all the string functions but it's really complicated for me to understand it all. A bunch of other admin commands do this to shorten up time it takes to execute each admin command.

It should figure out to ignore the admin prefix and separate the command from the "player quantity" but I'm very confused and I need ideas.

1 answer

✓ Accepted answer

You can use the string.gmatch() function to do this. It essentially returns an iterator which you can use in a for loop, you can find it’s usage in several places. You can learn more about string patterns on the wiki

local function split(content)
    local result = {}
    for word in content:gsub(“%S+”) do -- %S+ means a continuous pattern of non-space characters
        table.insert(result, word)
    end
    return table.unpack(result) -- Since you want a tuple
end

2 comments

0

Realised later you can also use word:split(“ “) which gives you the table directly

0

content:split(“ “)

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