Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How exactly does this string pattern "($%b{})" work?

Asked by 5 years ago

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

1 answer

Log in to vote
0
Answered by
Robin5D 186
5 years ago

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)

Ad

Answer this question