I am trying to make A GUI where you can Execute code, And I am trying to change the color of the word “game” to blue so it looks like you are coding in studio.
Note: I will be the only one that can Execute code.
You can accomplish this by splitting the target string using the `string.split` function, which takes a string and a separator as input and returns a table of substrings. In this case, we use the word `game` as the separator parameter to split the target string into separate substrings.
After that, we will be iterating through the returned substrings table and replace every substring with its corresponding number of spaces which is being done by getting the length of the substring and then repeat the space character using it as the number of repetitions in the `string.rep` function.
Finally, we reform the string using the table.concat function and giving it the `game` word as a separator parameter (that we had removed earlier using `string.split` function) to create a new string which have only the `game` word while other characters are replaced with spaces.
Here’s an example of how you might do it:
local function Highlight(Str: string)
if not string.find(Str, "game") then
return Str -- early exit.
end
local Splitted = string.split(Str, "game")
for i, SubString in ipairs(Splitted) do
Splitted[i] = string.rep(" ", #SubString)
end
return table.concat(Splitted, "game")
end
local Str = "Hello game game game game"
local Str_2 = "Hello! This is illegal text. game is not"
print(Highlight(Str)) -- outputs " game game game game"
print(Highlight(Str_2)) -- outputs " game "
local function Highlight(Str: string)
local MainPattern = "([^ ]+)" -- that pattern matches any sequence of characters except spaces.
local PuncPattern = "(%w+)(%p)" -- this one is used to remove any left punctuation (like a colon after the word "game,") using two captures, one for the Exempted word an another for any tailing punctuation.
local Replacement = " "
local Exempted = {
"game", "print"
}
Str = Str:gsub(MainPattern, function(Capture)
for _, Exception in ipairs(Exempted) do
if string.match(Capture, Exception) then
return Capture
end
end
return string.rep(Replacement, #Capture)
end)
Str = string.gsub(Str, PuncPattern, "%1") -- gets rid of tailing punctuation by just keeping the first captured group of the pattern.
return Str
end
local Str = "Hello game print test print"
local Str_2 = "game and game, print and game, print only..."
warn(Highlight(Str)) -- returns: " game print print"
warn(Highlight(Str_2)) -- returns: "game game print game print "
This approach uses the string patterns and the string function `gsub`. Also, you can add any other word to the Exempted table which would be ignored in the patterns.