String.split() help

Currently I am trying to create an admin panel for my game but I have ran into an issue with the command system. Since the swords in the game have spaces in them the string.split() is going to separate them making the item not be found anymore. Is there any way to reverse the split or figure another way to get the items.

Code:

ReplicatedStorage.Remotes:FindFirstChild("InvokeAdminCommand").OnServerInvoke = function(Player, CommandString: string)
	if table.find(Developers, Player.UserId) then
		local MessagedWords = string.split(CommandString, " ")
		
		if MessagedWords[1] == "/give" then
			local PlayerName = MessagedWords[2] -- Gets the player's Name
			local ItemType = MessagedWords[3] -- Gets the ItemType
			local Item = MessagedWords[4] -- Gets the ItemName
			
			local PlayerUserId = Players:GetUserIdFromNameAsync(PlayerName)
			
			if Players:FindFirstChild(PlayerName) then
				local Module = require(ServerStorage.Modules[ItemType .."Lib"])
				Module:Give(Player, ContentLibrary[ItemType][Item])
			end
		end
	else
		return
	end
end
1 Like

1: The issue with string.split() is that it’s messing up item names with spaces. To fix it you can use quotes around item names in the command.

Just update your code to something like this:

local PlayerName, ItemType, Item = string.match(CommandString, "^/give%s+(%S+)%s+(%S+)%s+\"(.-)\"$")

So now, you’d write the command like /give PlayerName Sword "Epic Sword of Destiny". This way, spaces in item names won’t be a problem.

2: Another fix could be limiting the amount of times you split the string:

function splitLimit(str, separator, limit)
    local result = {}
    local count = 0

    for match in (str..separator):gmatch("(.-)"..separator) do
        table.insert(result, match)
        count = count + 1
        if count == limit then
            table.insert(result, str:sub(#table.concat(result, separator) + #separator + 1))
            break
        end
    end

    return result
end

Just call it like so:

local MessagedWords = splitLimit(message, " ", 4)

3: Final and probably what you would want to use is:

MessagedWords[4] = table.concat(MessagedWords, " ", 4)
for i = #MessagedWords, 5, -1 do
   table.remove(MessagedWords, i)
end

This just adds all the indexes after 4 together into one and just removes the rest.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.