String.gsub() character escaping in a variable

I have a string variable of magic characters, therefore I can’t easily escape with %. I want string.gsub() to ignore the magic characters in this variable.

local text = "console.\"!()%l<>*-+\".numba \"hello?!\""

local quotes = {}
for quote in string.gmatch(text, "%b\"\"") do
	
	text = string.gsub(text, quote, "q")
    table.insert(quotes, quote)
end

-- I need the result to be "console.q.numba q"
-- and a table with all quotes {"!()%l<>*-+", "hello?!"}

I’m trying to replace all quotes in text with a placeholder, even if these quotes contain magic characters. One solution is to iterate through all characters in the quotes, but I’ve got a whole list of reasons as to why that is a bad idea. I’ve searched all over the devforum, even on other forums and Lua documentation, but I just can’t find my answer. So, for the first time ever, I’ve been defeated by a problem and I’m now asking the devforum for help.

In string.gsub(), how do I perform character escaping in a variable?

1 Like

I worked around this by replacing the loop with a single gsub, which can take a function by the way.

local text = "console.\"!()%l<>*-+\".numba \"hello?!\""
local quotes = {}
text = string.gsub(text, "%b\"\"", function(quote) table.insert(quotes, quote) return "q" end)

print(text)
3 Likes

OH WOW, the solution was so simple lol, I never knew string.gsub() takes functions thanks man

1 Like