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

I'm having trouble understanding why string.gsub() returns an weird error?

So I'm making my own admin commands and I am trying split chat messages by words using string.gsub() . I'm not sure how fully string.gsub() actually works but I know I have to use a string pattern to seperate the strings by spaces.

Someone told me a way to split/iterate through a string was like this:

local SpliceResult = {}
	
for word in string.gsub(ChatMessage, "%S+") do -- This is line 103
	table.insert(SpliceResult, word)
end

-- %S+ is a string pattern for seeing spaces in strings
-- ChatMessage is a variable for what the player said in chat
-- SpliceResult is a table holding the strings seperated into more strings by spacing

Now, it gives me a error that tells me of a "bad argument". So with my knowledge I may of put something other than a string, function or table. Here what it says directly:

ServerScriptService.AdminManager.CommandsModuleScript:103: bad argument #3 (string/function/table expected)

Since this is a function inside the admin scripts I checked and the parameters are all right. I'm not sure why the output gives a "bad argument" even though a ChatMessage is a string. I tested it and it's a string since I print debugged by saying:

print(type(ChatMessage))

--> string 

If there is any other way to split and iterate a string you can tell me in the comments section

1 answer

✓ Accepted answer

string.gsub() takes three arguments, the target string, the string pattern to replace and lastly what to replace the string pattern with (the third argument you miss). Looks like your problem is that you simply use the wrong function, you must use string.gmatch to iterate through occurrences of a string pattern:


local SpliceResult = {}

for word in string.gmatch(ChatMessage, "%S+") do -- This is line 103
    table.insert(SpliceResult, word)
end

Also, using string.gmatch() here, though equally effective, can be shortened using the string.split function:

local SpliceResult = ChatMessage:split(“ “) -- Gives the split strings as a table

1 comment

1

Thank you sorry for replying late I'll try it and see if it works

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