How to make a script that finds words used in a string from a table and then replaces the words with new one?
Here's my attempt:
local stringtofind = {'are', 'you'} local stringtoprocess = 'i think you are cool' local startvalue,endvalue = string.find(stringtoprocess,stringtofind) local firststring = string.sub(stringtoprocess,1,startvalue-1) local secondstring = string.sub(stringtoprocess,endvalue+1,string.len(stringtoprocess)) local stringtoinsert = "you're" local processedstring = firststring .. stringtoinsert ..secondstring print(processedstring) -- i want it to print "i think you're cool"
Any help?
You can pass dictionaries through gsub.
Example code:
local replacers = { ["hello"] = "ok", ["cool"] = "epic" } local old = "hello this is cool" local new = old:gsub("%S+", replacers) print(old) print(new)
Output:
>> hello this is cool
>> ok this is epic
In this case the string new
is old
but it replaced all words in the dictionary replacers
with each index's value. e.g. "hello"
is now "ok"
and "cool"
is now "epic"