lua-users home
lua-l archive

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


Cute. Presumably the answer you're looking for is "the user's request contains a %"

This is a more interesting implementation:

function getInput(word)
  io.write("What would you like to replace `",word,"' with?\n> ")
  return ( string.gsub(io.read"*l", "^%s*(.-)%s*$", "%1") )
end

function replaceUserInput(template)
  print(template)
  return ( string.gsub(template, "%$(.-)%$", getInput) )
end

> print (replaceUserInput "$Four$ score and $seven$ years ago")
$Four$ score and $seven$ years ago
What would you like to replace `Four' with?
> Six
What would you like to replace `seven' with?
> eight
Six score and eight years ago

> print (replaceUserInput "$Four$ score and $seven$ years ago")
$Four$ score and $seven$ years ago
What would you like to replace `Four' with?
> %4
What would you like to replace `seven' with?
> %7
%4 score and %7 years ago

On 26-Aug-05, at 8:55 AM, Aaron Brown wrote:

Antero Vipunen wrote:

I follow `escape magic characters everywhere' convention
(even if it is not necessary).

This is a respectable policy.  I don't follow it because I
find it easy to remember that only a select few characters
are magic within square brackets (this is also how POSIX
regular expressions work).  I do, however, usually follow
the policy of %-escaping nonmagical punctuation so I don't
have to remember Lua's (admittedly small) set of magic
characters, and also as a form of future-proofing.

On a similar topic, here's a quiz about a silly little
program:

io.write([[
"Four score XXX seven years ago"

What would you like to replace "XXX" with?

]])
local Input = io.read("*l")
Input = string.gsub(Input, "\n$", "")
local NewStr = string.gsub("Four score XXX seven years ago",
  "XXX", Input)
print(NewStr)

Under what circumstance will the program either disobey the
user's request or or actually error out?  What's the fix?

(Things don't work if the user enters a null byte, but
I'm interested in something else.)

--
Aaron