How to determine what letter was removed?

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

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

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
image

1 Like

Try removing the quotation marks from the end:

local lasterletterremoved

str = string.gsub(str, ".?$", function(n) lastletterremoved = n end)

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