Expanding Variables in User Input


(For all intents and purposes, this project is dead, but let us just call it "Deferred Indefinitely". Shall we?)

Problem

You have input a string with one or more variable references and you want to replace the variables with their values. For example:

target = "world"
  ==>"world"
"Hello, target!"
  ==>"Hello, world!"
exit

Solution

The easiest way is to substitute all variable references with a regex:

newstring = string.gsub(/\#{([\@\$\w]+)}/) {
  eval($1)
}

Discussion

This works if the variable is accessible from the current scope (local variable, instance variable, or global). There are probably safer methods to use than this, as someone could probably concieve of some nasty hack that would match the regular expression, and then have it eval-ed by this solution.

TODO: look for alternate methods. Preferably look up the variable.

Contrast

In perl, you'd do roughly the same thing, but use the s///gee form to double evaluate the substitution in order to perform the lookup.

Related

TODO: LIST_OF_RELATED_ITEMS

Status: In Progress