示例工程 10-pattern-matching
10-pattern-matching/02-gsub-function-table/main.lua
-- @runtimes lua54 luajit
--- 演示:gsub 用函数或表做替换。
local M = {}
--- @return table { function_result = string, table_result = string }
function M.run(log)
log = log or print
local source = "a=1 b=2"
local function_result = source:gsub("(%a)=(%d)", function(key, value)
return key .. ":" .. tostring(tonumber(value) * 2)
end)
local replacements = { a = "A", b = "B" }
local table_result = source:gsub("(%a)=", function(key)
return replacements[key] .. "="
end)
log(("function_result=%s"):format(function_result))
log(("table_result=%s"):format(table_result))
return { function_result = function_result, table_result = table_result }
end
if not ... then
M.run()
end
return M