string replacement problem.

Posted by Maxhrk on Thu 20 Dec 2007 01:25 AM — 2 posts, 13,300 views.

USA #0

local replacements = { 
   ['\\'] = "\\",
}

function toreplace(s)
	local result
	if type(s) == "string" then
	result = string.gsub (s, "%a+", 
				function (str) 
					return replacements [str] 
				end)
	return result
	else
		message.console("toreplace function: it is not a string.")
	end --if
end -- toreplace



when it display on my screen like this:

trigger:^You are tempered against fire damage.$


when it supposedly display like this:

trigger:^You are tempered against fire damage\.$


how to display '\' properly?

thanks!
Amended on Thu 20 Dec 2007 01:28 AM by Maxhrk
Australia Forum Administrator #1
This is unnecessarily complicated for a start.

string.gsub will accept a table as the replacements argument, and substitute something found in the table for the replacement.

eg.


t = { cat = "dog", 
      mouse = "tiger" }

print ((string.gsub ("You see a cat and a mouse", "%a+", t))) --> You see a dog and a tiger



Your second problem is that you are searching for a backslash, and if found, replacing it with a backslash. What will that achieve?

Your third problem is that you are searching for "%a+" which is alphabetic characters. Thus it will never match on backslash anyway.

Something like this will achieve what I think you are trying to do:


test = "^You are tempered against fire damage.$"

test = string.gsub (test, "[^A-Za-z0-9 ]", "\\%1")

print (test)  --> \^You are tempered against fire damage\.\$


What I am searching for here is everything that is not A-Z or 0-9, or a space, and doing the replacement. Note how the tilde and $ got replaced too.