Lua 用函数替换字符串

Lua replace string with function

我想用一些函数替换匹配的字符串。

我已使用“%1”查找字符串,但无法使用匹配的字符串。

print(text) 显示 %1,不匹配的字符串。

original_text = "Replace ${test01} and ${test02}"

function replace_function(text)
    -- Matched texts are "test01" and "test02"
    -- But 'text' was "%1", not "test01" and "test02"
    local result_text = ""

    if(text == "test01") then
        result_text = "a"
    elseif(text == "test02") then
        result_text = "b"
    end

    return result_text
end

replaced_text = original_text:gsub("${(.-)}", replace_function("%1"))

-- Replace result was "Replace  and"
-- But I want to replace "Replace ${test01} and ${test02}" to "Replace a and b"
print(replaced_text)

如何在 gsub 中使用匹配的字符串?

问题是 replace_functiongsub 可以启动 运行 之前被调用。 replace_function 不知道 %1 是什么意思,return 也不是对 gsub.

有任何特殊意义的字符串

但是,gsub doc 中的以下信息告诉我们,您可以将 replace_function 直接传递给 gsub

If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order.

original_text:gsub("${(.-)}", replace_function)