lua-users home
lua-l archive

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


It was thus said that the Great Jonas Thiem once stated:
>
> Alternatively, I'm also happy for easier solutions to get this
> behavior of gsub if this is already possible in an easier way that I
> haven't seen.

  You could try the following:

	lpeg = require "lpeg"

	function replace(s,this,that)
	  local trans = lpeg.Cs(((lpeg.P(this) / that) + lpeg.P(1))^0)
	  return trans:match(s)
	end
   
	print(replace("target string","get","ball"))
	print(replace("100% efficiency with 20% effort","%"," per cent"))
	print(replace("ababababababa","ababa","xx"))

  Yes, it has a dependency on LPeg.  But it's simple, and it works as
expected, without any problems of escaping "special" characters.

  -spc