lua-users home
lua-l archive

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


What do I do wrong?

Probably the error is because string.gsub, when called with it's third argument as an string, use that as a replacement string.

From the manual:

"string.gsub (s, pat, repl [, n])

(...)

If repl is a string, then its value is used for replacement. Any sequence in repl of the form %n, with n between 1 and 9, stands for the value of the n-th captured substring (see below).

(...)

   x = string.gsub("hello world", "(%w+)", "%1 %1")
   --> x="hello hello world world"

   x = string.gsub("hello world", "(%w+)", "%1 %1", 1)
   --> x="hello hello world"

(...)"



So, you need to escape those magic characters ('%'):


function log(date,msg)
   pat = "%date %str"
   ostr = string.gsub(pat,"%%date",date)
   ostr = string.gsub(ostr,"%%str",(string.gsub(msg, '%%', '%%%%')))
   print(ostr)
end

log(os.date(),"strange string %4 is this")


Please note that the inner gsub (the one that escapes '%') is enclosed with parenthesis to avoid supplying a fourth argument to the outer gsub ("n", maximum number of substitutions)

--rb