lua-users home
lua-l archive

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


Kein-Hong Man's solution worked. His solution was to escape the percent signs 
in the pattern. More at the end of this email...

On Sunday 02 January 2011 20:40:11 KHMan wrote:
> On 1/3/2011 9:21 AM, Steve Litt wrote:
> > [snip]
> > 	str = string.gsub(str, v, response)
> >
> > ******************************************
> > slitt@mydesk:~/ulua/program$ ./test.lua
> > B4 , str=>mycommand %c%Carg please=>%% %b%Barg please=>%% %a%Aarg
> > please=>%% final args
> > Aarg please=>al
> > %a%Aarg please=>%%
> > al
> 
> v = "%a%Aarg please=>%%"
> response = "al"
> 
> string.gsub() wants a pattern for the second operand. But you want
> to use v as a literal. So you need to escape those "%" (and
> perhaps other magic characters) and make gsub interpret v as a
> literal.
> 
> "%a%Aarg please=>%%" => "%%a%%Aarg please=>%%%%" (I think)
> 

Kein-Hong Man, you were right. For some reason I figured if the pattern was in 
variable then it didn't have to be escaped, but of course this is wrong. So I 
added and used a function called string2pattern, as shown below:

=======================================
function string2pattern(str)
	return string.gsub(str, "%%", "%%%%")
end

str = "mycommand %c%Carg please=>%% %b%Barg please=>%% %a%Aarg please=>%% 
final args"

local words = {}
local w
for w in string.gfind(str, "%%.%%.-%%%%") do
	table.insert(words, w)
end

table.sort(words, function (a, b)
	return string.lower(a) < string.lower(b)
end)

io.write("B4 , str=>"); print(str)
local k,v
for k,v in ipairs(words, k) do
	local temp = string.gsub(v, "%%.%%", "")
	temp = string.gsub(temp, "%%%%", "")
	io.write(temp)
	local response = io.read()
	str = string.gsub(str, string2pattern(v), response)
end
io.write("Aft, str=>"); print(str)
=======================================

Here's the session:

*********************************
slitt@mydesk:~/ulua/program$ ./test.lua
B4 , str=>mycommand %c%Carg please=>%% %b%Barg please=>%% %a%Aarg please=>%% 
final args
Aarg please=>al
Barg please=>ben
Carg please=>cim
Aft, str=>mycommand cim ben al final args
slitt@mydesk:~/ulua/program$
*********************************

Obviously for a more robust program I'd need string2pattern() to escape more 
characters than just the percent sign, but for the purposes of UMENU what I've 
done should be enough.

I might tighten it up a little bit so as not to disturb single percent signs.

Thanks

SteveT

Steve Litt
Recession Relief Package
http://www.recession-relief.US
Twitter: http://www.twitter.com/stevelitt