V_lidus
(xda)
August 12, 2024, 9:42pm
1
So I’m using string.gsub to remove the last letter in a string, however I was wondering if there would be a way to also determine what letter was removed and print it?
str = string.gsub(str, ".?$", "") --need to know what letter was removed
print(str)
1 Like
6mikael6
(6mikael6)
August 12, 2024, 10:04pm
2
You can pass a function as the third argument in string.gsub() where the first variable given to the function is the matched pattern:
local str = "Test string!"
string.gsub(str, ".$", function(n) print(n) --[[ Prints: "!" ]] end)
You can also return a string that the matched pattern should be replaced with:
local str = "Test string!"
str = string.gsub(str, ".$", function() return "." end)
print(str) -- Prints: "Test string."
1 Like
V_lidus
(xda)
August 12, 2024, 10:10pm
3
Okay, this is good. However I need to be able to assign that letter that was removed to a separate value so I can search for it later.
local lasterletterremoved
str = string.gsub(str, ".?$", function(n) lastletterremoved = n "" end)
^ This didn’t work
1 Like
6mikael6
(6mikael6)
August 12, 2024, 10:13pm
4
Try removing the quotation marks from the end:
local lasterletterremoved
str = string.gsub(str, ".?$", function(n) lastletterremoved = n end)
V_lidus
(xda)
August 12, 2024, 10:15pm
5
This just prints what the last letter is though, it doesn’t actually remove it.
EDIT: Fixed, this way worked better:
lastletterremoved = string.match(str, ".?$")
str = string.gsub(str, ".?$", "")
This way I have the last letter removed to reference, and it still removes it as normal.
1 Like