:match being broken?

  1. What do you want to achieve? :match to return the match because there is a match

  2. What is the issue? :match is returning nil, even though when you compare both strings, it returns true as they are the same string but :match is returning nil for some reason

local str1 = "local digit = string.sub(str, i, i)" local str2 = "local digit = string.sub(str, i, i)" print(str1:match(str2))


It’s because parentheses are ignored in :match(). It doesn’t detect anything with function calls and parentheses.

1 Like

is there any solution to this?

Your best bet would be to use another type of identifier like a punctuation “!” and “@” to denote paranthesses and then use string.gsub to replace the dot.

Screen Shot 2022-12-10 at 9.47.10 AM

Precede special characters with the % symbol to ‘escape’ them:

local str2 = "local digit = string%.sub%(str, i, i%)"

Here’s a function to do that automatically:

local function sanitize(input)
    return input:gsub("([%$%%%^%*%(%)%.%[%]%+%-%?])", function(char) return "%"..char end)
end

Here’s how you would use it.

local str1 = "local digit = string.sub(str, i, i)"
local str2 = "local digit = string.sub(str, i, i)"
print(str1:match(sanitize(str2)))

Specifically it’s because special characters do special things.

String patterns are super useful in string handling and I highly recommend learning them.
By knowing them, you can replace str2 with this:

local str2 = "local%s+digit%s*=%s*string%.sub%(%s*str,%s*i,%s*i%s*%)

which matches any of the following

local digit = string.sub(str, i, i)
local digit=string.sub(     str,    i, i   )
local      digit     =string.sub(str,i,i     )
3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.