lua-users home
lua-l archive

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


On 7 April 2015 at 22:01, 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

Cool variation on the idea!

I like your additional test cases; I originally left those open in
case someone came up with a cool solution that depended on some
stranger behavior in some of those.

In terms of functionality, I think I'd prefer "$fooend" to expand to
"" (undefined vars expand to empty string a la bash); this would
result in the following (even shorter!) variation for Soni L.'s latest
solution:

local function expand_variables(str)
    return str:gsub("%$({?)([A-Za-z0-9_]+)(}?)", function(a,b,c)
           return #a <= #c and (variables[b] or "") .. (#a < #c and c or "")
   end)
end

-- Hisham