I’m new to Lua.
Say i have a string “1234567890”.
I want to iterate over all possible 3 digit numbers. (ie 123,234,345,456....)
for m in string.gmatch("1234567890","%d%d%d") do
print (m)
end
But this gives me the output 123,456,789.
What kind of Pattern should i be using?
And secondly, a related question, how do i specify a 3-digit number? "%3d" doesn’t seem to work. Is "%d%d%d" the only way?
Note: This isn’t tagged Regular expressionbecause Lua doesn’t have RegExp. (atleast natively)
Thanks in advance 🙂
Update: As Amber Points out, there is no “overlapping” matches in Lua. And, about the second query, i’m now stuck using string.rep("%d",n) since Lua doesn’t support fixed number of repeats.
gmatchnever returns overlapping matches (andgsubnever replaces overlapping matches, fwiw).Your best bet would probably be to iterate through all possible length-3 substrings, check each to see if they match the pattern for a 3-digit number, and if so, operate on them.
(And yes,
%d%d%dis the only way to write it. Lua’s abbreviated patterns support doesn’t have a fixed-number-of-repetitions syntax.)