Difference between pages "Module:String" and "Module:String/sandbox"
(Difference between pages)
m (1 revision imported) |
(Module Creation) |
||
Line 165: | Line 165: | ||
end | end | ||
− | local iterator = mw.ustring.gmatch(s, pattern) | + | local iterator = mw.ustring.gmatch( s, pattern ) |
if match_index > 0 then | if match_index > 0 then | ||
-- Forward search | -- Forward search | ||
Line 177: | Line 177: | ||
else | else | ||
-- Reverse search | -- Reverse search | ||
− | local | + | local match_buffer = {} |
− | local | + | local index = 1 |
+ | match_index = -match_index | ||
+ | |||
for w in iterator do | for w in iterator do | ||
− | + | match_buffer[index] = w | |
− | count = | + | |
+ | -- Circular buffer with length 'match_index' | ||
+ | -- Wraps around to overwrite matches too old to be the result, | ||
+ | -- so memory use is O(match_index) and not O(total match count)) | ||
+ | index = (index == match_index) and 1 or (index + 1) | ||
end | end | ||
− | result = | + | -- 'index' is now at oldest element, which next iteration would have |
+ | -- overwritten. If 'match_buffer' has fewer than 'index' elements, | ||
+ | -- there were too few matches; the resulting nil is handled below. | ||
+ | result = match_buffer[index] | ||
end | end | ||
end | end |