lua-users home
lua-l archive

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




On 07/04/15 09:45 PM, Hisham wrote:
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

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



-- Hisham


--
Disclaimer: these emails are public and can be accessed from <TODO: get a non-DHCP IP and put it here>. If you do not agree with this, DO NOT REPLY.