lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


(I really should check for new messages in the thread before replying... :-P)

On Tue, Apr 7, 2015 at 9:01 PM, Jonathan Goble <jcgoble3@gmail.com> wrote:
> On Tue, Apr 7, 2015 at 8:12 PM, Hisham <h@hisham.hm> wrote:
>>    -- At your discretion: how to deal with...
>>    -- "$fooend"
>>    -- "${}"
>>    -- "${bo{bozo}zo}"
>>    -- "${bo${bar}zo}"
>
>
> I set up the following test cases for those, plus two more:
>
> { from = "$fooend", to = "$fooend" }, -- ignore undefined vars
> { from = "${}", to = "${}" }, -- ignore empty braces
> { from = "${bo{bozo}zo}", to = "${bo{bozo}zo}" }, -- too weird, ignore
> { from = "${bo${bar}zo}", to = "${bofoozo}" }, -- expand the innermost one
> { from = "test ${foo", to = "test ${foo" }, -- ignore unclosed braces
> { from = "test $bar}bar", to = "test foo}bar" }, -- don't strip the stray brace
>
>
> With those and the variables and test cases you defined, this shorter
> function passes all tests:
>
> local function expand_variables(str)
>     return str:gsub("%$(%{?)([A-Za-z0-9_]+)(%}?)", function(open, var, close)
>         if #open == 1 and #close == 0 or not variables[var] then
>             return "$"..open..var..close
>         else return variables[var] .. (#open == 0 and close or "")
>     end end)
> end
>
> Of course, I could have explicitly checked for open == "{", etc., but
> #open == 1 is one keystroke shorter, and this is golf. :-)
>
> Jonathan