I am working on a library extension module, and a function I really wanted was a function that interpolates variables into a string with JavaScript's syntax `${variable}`.
I used interp
from http://lua-users.org/wiki/StringInterpolation, and customised it a bit to fit my coding style:
interpolate = function(s, vars) return (s:gsub("($%b{})", function(var) return vars[var:sub(3, -2)] or error(string.format("%s not defined", var:sub(3, -2))) end end
But I'm not too sure how it works.
Here are my questions:
Why does $
not precede a %
sign if it's a special character? Doesn't it anchor a pattern to the end of a string?
What is the difference in using parentheses directly without "%b"
?
For your 1st question, I have no clue.
For your 2nd question, I looked at what %b does. If you use parentheses without %b, then the pattern won't work if anything is in between the parentheses. If you use %b, anything in between does not affect the pattern. To describe %b better:
The balanced capture, matching x, y, and everything between (for example, %b() captures a pair of parentheses and everything between them)