I am trying to make a script that would look for letters and then something after it, and then identify that as something and change it.
For example, !smile would be turned into :)
It would look for the exclamation, and then read after it until a space.
Or !sad would be :(
I cannot figure out how to do this and would like to know if there were certain properties of strings or a way to look into strings?
The best way to do this is definitely with String Patterns. Using the match
or gmatch
function in the string library, you can look for substrings that match a given string pattern.
In your comment you said something about finding numbers with a letter after them that represents the number of trailing zeros, like "82k" for example. We can do this using the string pattern "%d+k"
, which finds any number of digits followed by a 'k' character. So then we want to replace the 'k' with three zeros. We can do that by getting the substring of all the characters and concatenating on the final zeros.
Script
local capture = string.match("82k", "%d+k") local amount = string.sub(capture, 1, -2) .. "000" print(amount)
Output
82000
What if we want to do this for multiple values? The easiest way to do this is with the gmatch
function. This function will return an iterator function (e.g. pairs and ipairs) which will return every capture found in the string. Lets do the same thing as we did before, except this time we will parse through a list of numbers.
Script
local values = "82k, 14k, 102k, and 43k" for capture in string.gmatch(values, "%d+k") local amount = string.sub(capture, 1, -2) .. "000" print(amount) end
Output
82000 14000 102000 43000
So lets move onto substituting your emoticons. We are going to use a different function here called gsub
, also in the string library. This function will return a copy of the string with all of substrings captured by the string pattern. We will use explicit string pattern for both of the smile and sad emoticons, i.e. "!smile" and "!sad".
Script
local message = "!sad!sad Oh hello there! !smile!smile" message = string.gsub(message, "!smile", ":)") message = string.gsub(message, "!sad", ":(") print(message)
Output
:(:( Oh hello there! :):)
As you can see, string patterns are extremely powerful tools to utilize when doing string manipulation. I highly recommend going through the wiki article I linked at the top of this answer and looking over the different quantifiers, anchors, sets, and captures to see how powerful they are.