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"?
