[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: A little bit of golf
- From: Matthew Wild <mwild1@...>
- Date: Wed, 8 Apr 2015 10:55:34 +0100
On 8 April 2015 at 01:12, Hisham <h@hisham.hm> wrote:
> Hi all,
>
> So here's a little problem that some of you might enjoy playing with
> in case you're bored.
>
> Let's play "variable expansion". We want to convert "Hello, $planet!"
> to "Hello, Earth!" given { planet = "Earth" }, but we also want it to
> support "Hello, ${planet}!".
>
> That is, we want to perform "variable expansion" in a string s, so
> that given a table of "variables" we want to expand every $foo or
> ${foo} in s to the value of variables.foo.
...
> Can you suggest any nicer and/or shorter solution?
Well, it's the middle of the night and I can't sleep, but this passes
all your tests, and all other tests posted in the thread so far
(except "$undefined" expands to "" rather than "$undefined", as you
requested):
local function expand_variables(str)
return (str:gsub("%$([_%w]+)", "${%1}"):gsub("%${([_%w]+)}", function (v)
return variables[v] or "";
end));
end
Regards,
Matthew