Note: This blog post only scratches the surface and focuses on a specific use case. You should read the documentation at Lua.org for a complete overview.
Before we get started, thank you for taking the time to read my post. Now for a bit of String Manipulation (keeping this brief).
For our use case, we will be reviewing admin commands from a user but we will focus on the text manipulation side instead of the UI and all those shinanigans. Let’s say we have a way to recieve Text input from the user, have it saved into a variable and we want to have our script find certain keywords in said text:
local userSaid = "/kill somePlayer"
For this example, we want to:
A) Know what admin comamnd the user is invoking.
B) What parameters we need to pass to the admin command.
We won’t focus on B as that would require us to have a full script setup which we currently do not. For A on the other hand…
For this we will be using `.gmatch()` as you may see from the documentation it returns an iterator function which we can use to loop through each word. Like this for example:
local test = "/kill somePlayer"; for word,_ in string.gmatch(test,"(.%a+)") do print(word) end
If we were to place that in the command bar we would get this in the output window:
Now to further expand on the for loop. Normally, we would create a function outside the for loop where we could pass it the command so that we know what to do with the arguments ( from B) but that’s another topic for another day. Let me explain the expression used. “(.%a+)” is the expression, “()” is used to capture everything inside as a group, if they aren’t exactly how the expressions inside describes them it won’t be returned, “.” returns any character, “%a” returns any letter, “+” matches one or more of the previous class, in this case it’ll be “%a”.
Basically, we are telling it to find any character type (letter or non-letter) at the beginning with one or more letters following it as a group.
Now we get the word by using match:
local foundSlash = string.match(word,"/%a+")
To further expand this, we can now remove the forward-slash by using a set. “[^/]” like so:
local test = "/kill somePlayer"; for word,_ in string.gmatch(test,"(.%a+)") do local foundSlash = string.match(word,"/%a+") if foundSlash then local commandWord = string.match(word,"[^/]%a+") print(commandWord.." is a command!") end end
Here is the output:
And that concludes this post, you can now further expan this idea and add functions which will run a specific command based on the word the user gave it. Thank you for reading, i hope you enjoyed your stay.