lua-users home
lua-l archive

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


2015-04-08 2:12 GMT+02:00 Hisham <h@hisham.hm>:
> 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.
>
> HOWEVER, we don't want recursive expansion (ie, if the value of
> variables.foo is "$bar", then we _don't_ want it expanded to the value
> of variables.bar).

I.e. you wish to remove the restriction on the third line
of the docstring of ml.expand (from Microlight).

--- expand a string containing any `${var}` or `$var`.
-- If the former form is found, the latter is not looked for, so
-- pick _either one_ of these forms consistently!
-- Substitution values should be only numbers or strings.
-- @param s the string
-- @param subst either a table or a function (as in `string.gsub`)
-- @return expanded string

> Can you suggest any nicer and/or shorter solution?
>
> Ah! NO LPEG ALLOWED! :)

math.randomseed(os.clock())
function password()  return (("."):rep(32):gsub(".",
  function() return string.char(math.random(256)-1) end))
end

Now make two tables: one containing the original keys
and a password for each, the other containing those
passwords as keys with the original values.

Three times gsub:
  the ${var} forms with the first table,
  the $var forms with the first table,
  the passwords with the second table.

If you are scared this might not work, better not use
ATMs any more either.