lunarmodules / Penlight

A set of pure Lua libraries focusing on input data handling (such as reading configuration files), functional programming (such as map, reduce, placeholder expressions,etc), and OS path management. Much of the functionality is inspired by the Python standard libraries.
https://lunarmodules.github.io/Penlight/
MIT License
1.93k stars 241 forks source link

Can't use % as escape character in a template #451

Closed dargueta closed 1 year ago

dargueta commented 1 year ago

Suppose we have the following code:

tpl = [[
% for k, v in pairs(values) do
$(k) = $(v)
% end
]]

text = template.substitute(
    tpl,
    {
         _escape = '%',
         _parent = _G,
        values = {a = 1, b = 2, c = 3}
    }
)
print(text)

It appears the escape has no effect:

% for k, v in pairs(tbl) do
 = 
% end

If we use something else, like !, we get the expected result:

c = 3
a = 1
b = 2

I think we can fix this by passing plain=true to the strfind() calls here, e.g.

-- Instead of this:
local _, e, lua = strfind(chunk,esc_pat1, s)

-- Do this:
local _, e, lua = strfind(chunk,esc_pat1, s, 1, true)

Environment: OS: Ubuntu 22.04 Lua: 5.4.4 Penlight: 1.13.1

alerque commented 1 year ago

Can you send a PR for this? I think you fix looks like it will be correct, but we'll want to see some test results, which a PR should show us.

dargueta commented 1 year ago

Done: https://github.com/lunarmodules/Penlight/pull/452

After a bit of tinkering I realized I needed to use string escaping rather than a literal search so that the inline escape would work as well.

dargueta commented 1 year ago

Fixed by #452