[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: A little bit of golf
- From: "Soni L." <fakedme@...>
- Date: Tue, 07 Apr 2015 22:09:44 -0300
On 07/04/15 09:58 PM, Soni L. wrote:
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
Wait derp, that == should be <= :P
And to also fit the following cases:
{ 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
Should probably do "and variables[b] and variables[b] .. (#a < #c and c or "")" instead.
Final result:
local function expand_variables(str)
return str:gsub("%$({?)([A-Za-z0-9_]+)(}?)", function(a,b,c)
return #a <= #c and variables[b] 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.