String Patterns & Iterators
The string.match function is great, but it will only find one occurrence of a given pattern. Luckily, we have a function called string.gmatch, which can be used as an iterator function in a for loop. This means it will not only return a given string pattern, but it will return the next occurrence of that same pattern as well. Here's an example:
local command = "ban user 10d reason"
local arguments = {}
for chunk in string.gmatch(command, "%S+") do
arguments[#arguments + 1] = chunk
end
print(arguments[1])
print(arguments[2])
print(arguments[3])
print(arguments[4])
You should look into character classes and what they mean. %S+ means "get every character and stop when there's a space character" However, ROBLOX recently added string.split to the string library, so the above code can be simplified like such:
local command = "ban user 10d reason"
local arguments = string.split(command, " ")
print(arguments[1])
print(arguments[2])
print(arguments[3])
print(arguments[4])
Real Solution
The above options are good and should be used in other cases, but they still don't fully solve your problem. Since you want your last command argument to be a sentence, you shouldn't just use string.split because that will also break apart your reason sentence.
I'll create a function that splits a command string into 4 components:
- Command Name
- User Argument (what user the command is effecting)
- Arg1 (some extra information)
- Arg2 (some more extra information)
local command = "ban user 10d you've been bad"
local function getCommandArgs(cmd)
return command:match("(%S+)%s(%S+)%s(%d+%S+)%s(.+)")
end
local cmdName, userName, arg1, arg2 = getCommandArgs(command)
print(cmdName)
print(userName)
print(arg1)
print(arg2)
There are many ways to do this, by the way, so don't get intimidated by the long scary string pattern. You'll get it eventually. All it's doing here is getting the first word (%S+), then waiting for a space character(s), %s, then getting the second word, (%S+), then waiting for another space character, %s, then getting the third word (which is really the date argument), (%d+%S+), then waiting the space character(s) after that, %s, then finally, just getting any and every character after that (.+).
The reason why the date argument is %d+%S+ is because %d+ matches only numbers, and the time should always start with a number. The modifier after the number is the minutes/hours/days/weeks/whatever, which will be some alphabet characters that we can match with %S+. Thus, %d+%S+ will match 10d or 10w, and so on.
Again, I recommend looking into string patterns. They're quite fun! If you have any questions, let me know and I'll be happy to answer.
1 comment
I get it! Now I finally understand what all the crazyness with the %d, %s, %., etc mean! Thank you so much for your help, solved my problem and I learned for future reference!