lua-users home
lua-l archive

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


On 7 April 2015 at 21:24, Soni L. <fakedme@gmail.com> wrote:
>
> expand_variables = function(str)
>    return str:gsub("%$({?)([A-Za-z0-9_]+)(}?)", function(a,b,c)
>       -- little trick with the lengths, if a matches then it'll be 1, if c
>       -- doesn't match it'll be 0 and 1 <= 0 is false, thus returning false
>       -- and keeping the match as-is. for both matching, 1 <= 1 is true, so
>       -- you get variables[b]. for neither matching, 0 <= 0 is true, so you
>       -- get variables[b].
>       -- ps: you never asked us to handle "$foo}" so I decided to eat the }
>       return #a <= #c and variables[b]
>    end)
>
> end

Nice! If we _were_ to handle "$bar}" returning "foo}", how would you
do it? The variation I came up with was not as elegant:

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

-- Hisham