Home > front end >  How to replace string in lua?
How to replace string in lua?

Time:01-06

My question is how can I replace the character from a given string? If someone says something in the chat, and that word is a bad word then replace it with "****". I don't know how to approach the print section.. Because I've got the index of the badword but I don't know how to replace it from the original message.

local badwords = {
    "badword",
    "badword2",
}

function(msg)
   local message = msg;
   local lowered_msg = message:lower(); 

   for index, val in pairs(badwords) do 
       if lowered_msg:match(val) then
           local indexStart, indexEnd = string.find(lowered_msg, val)
           print(message:gsub(indexStart, "*****", indexEnd))
       end
   end
end 

CodePudding user response:

The gsub function takes three arguments:

  • the string to be modified,
  • the pattern to be replaced,
  • and the replacement string,

so you need to do something like this:

message = string.gsub(message, message:sub(indexStart, indexEnd), "*****")
print(message)
  • Related