示例工程 10-pattern-matching
10-pattern-matching/05-gsub-count/main.lua
-- @runtimes lua54 luajit
--- 演示:gsub 的替换次数与函数返回 false 保留原匹配。
local M = {}
--- @return table { replaced = string, count = integer }
function M.run(log)
log = log or print
local source = "a1 b2 c3"
local replaced, count = source:gsub("%d", function(digit)
local value = tonumber(digit)
if value % 2 == 0 then
return nil
end
return "*"
end)
log(("replaced=%s count=%d"):format(replaced, count))
return { replaced = replaced, count = count }
end
if not ... then
M.run()
end
return M