r/lua • u/drunken_thor • Feb 12 '26
Lua string.match quirks!
Hey I have been developing 100% lua 5.1 compat for practice and I ran into these weird outputs of string.match while writing the compatibility tests that I would love some explanation if anyone knows why. I have even read the source code and I have no idea why it is made this way.
string.match("alo xyzK", "(%w+)K") == "xyz"
string.match("254 K", "(%d*)K") == ""
string.match("alo ", "(%w+)$") == nil
Why does the second match return an empty string but the third returns nil? They both don't match the pattern, they both have capture groups that match some of the string but not the whole pattern. I have also noticed that if the + in the second pattern is changed to a * it will return an empty string.
string.match("alo ", "(%w*)$") == ""
I would love some insight if anyone has it.
Edit 1:
- updated lua version
Clarification I do not mean why doesnt the pattern match, I mean why on two different patterns that do not match do they return nil or an empty string. Why would they both not return nil or both return an empty string because they did not match.
EDIT 2: Solution
I understand now "(%d*)K" does actually match the string because The K matches and the characters before it are 0 or more numbers. There are 0 numbers so the captured group is an empty string. Whereas "(%w+)$" returns nil for "alo " because (%w+)$ there are no letters before the end of the string and they are 1 or more so at least one is required.
View all comments
Show parent comment
2
u/appgurueu Feb 13 '26
If you're asking whether PUC Lua's implementation of pattern matching (the reference implementation) is "stupid" in that it will not exploit the end-of-string anchor to actually match from the end of string, the answer is yes; it is a very naive implementation.
You can test this yourself by doing something like the following in the REPL:
Will
s:reverse():match"^a"be faster? Probably not. This depends on the constant factors of pattern matching versus string reversal. But both things need to look at the entire string, which is basically not what you want when checking for a short suffix pattern.Doing this more efficiently would be best done by a better pattern matching implementation.