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

Simple string manipulation script not working?

local maps = game.ReplicatedStorage.Maps
local player = game.Players.LocalPlayer
local mapcommand = "!load"

player.Chatted:connect(function(Chat)
if Chat:lower():sub(1,mapcommand:len()) == mapcommand then
local newMap = maps:FindFirstChild(Chat:sub(Chat,1+mapcommand:len()))
print(newMap)
end
end)

The purpose of this script is to take a command a player chatted, find the map they wish to load, and then print the map's name.

Players.Player1.PlayerGui.System Messages:148: bad argument #1 to 'sub' (number expected, got string)

Help would be greatly appreciated!

3 comments

0

It needs to be chat:sub() not chat.sub() on line 7.

0

Thanks for pointing that out. Still doesn't work though.

0

Is it a local or regular script? Where is it located in the game?

1 answer

The problem you have is that you are giving a string e.g.

Chat:sub([string] , [number])

All you needed to do is use a number e.g.

Chat:sub([number] , [number])

This is only an example script I mad in 2 mins I did not include maps , this only shows a better way for looking using a list of command.

local chatMsg = " bad chat msg" -- test bad msg
local chatMsg2 = "!load Radndom" -- test good msg

local chatCmds = { -- list of all command
	"!load", "!save", "!reload" -- keep all in lower case
}

-- a function to check if a  msg has a cmd
local function isCmd(msg)
	local frmMsg = msg:lower()	-- clean up the msg for processing
	
	for i, v in pairs(chatCmds) do -- loop of commands
		if frmMsg:sub(1, v:len()) == v then -- only get the command length of the msg then compare to expected command
			return true, frmMsg:sub(2, v:len()), frmMsg:sub(v:len()+1)  -- command found return success, command withouf the ! , data after this cammand
		end
	end
	
	return false, "","" -- no command found
end

local suc, cmd, data = isCmd(chatMsg) -- test a bad command

if suc then
	print(cmd .. " " .. data)
else
	print("Fail")
end

local suc2, cmd2, data2 = isCmd(chatMsg2) -- test a good command
if suc2 then
	print(cmd2 .. " " .. data2)
else
	print("Fail")
end

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