Search code examples
luastring-matchinglua-patternsluajit

How do I get lua string match to parse an environment variable string?


I have a config file parser written in lua.

I'd like to detect values that are environment variables and change them with os.getenv.

It's probably a bit ambitious because I can have values like

"a string with an embedded ${VARIABLE} in here"

or

"another string with an env $VARIABLE"

And I should probably allow escaping them with double $$ to allow a literal $.

How do I do this?

This is what I have so far, but it isn't right

local envvar = string.match(value, "%$([%w_]+)")
if envvar then
  print("Envvar=", envvar)
  value = value:gsub("(%$[%w_]+)", os.getenv(envvar))
end

For example, I can't figure out how to use the %b balance option here to properly match { } combinations. And make them optional. How do I make this work robustly?

In fact, I realise it's probably more complicated than this. What if more than one environment variable was specified?


Solution

  • local text = [[
    Example: ${LANG}, $TEXTDOMAINDIR, $$10.00, $$LANG, $UNDEFINED
    Nested braces: {{${SHELL}}}
    ]]
    text = text:gsub('$%$','\0')
               :gsub('${([%w_]+)}', os.getenv)
               :gsub('$([%w_]+)', os.getenv)
               :gsub('%z','$')
    print(text)
    --> Example: en_US.UTF-8, /usr/share/locale/, $10.00, $LANG, $UNDEFINED
    --> Nested braces: {{/bin/bash}}