Jump to content

Module:Sandbox/Matroc/Str swap

From Wikipedia, the free encyclopedia
local p = {}

function p.swapreplace(frame)
    local a_string = frame.args[1] or ""
       if a_string == nil  or a_string == "" then
         error("Missing string on which to perform swap!")
        end

    local noofargs = 0
       for i = 1, 10, 1 do
          if frame.args[i] ~= nil then
            noofargs = i
           end -- END if
        end -- END for

       if noofargs ~= 4 then
         error("Incorrect number of arguments: " .. noofargs .. " Required = 4!")
        end -- END if

    local nooftimes = tonumber(frame.args[4])

       if nooftimes == nil then
              nooftimes = 1
          elseif nooftimes == "" then
              nooftimes = 1
          elseif nooftimes <= 0 then
              nooftimes = 1
        end

    local swap = frame.args[2] or ""

          if swap == nil then
             swap = ""
           end

          if swap == "" then
             error("Missing String to Swap!")
           end

    local swapwith = frame.args[3] or ""

          if swapwith == nil then
             swapwith = ""
           end

          if swapwith == "" then
             error("Missing String to Swap with!")
           end


     a_string = (a_string:gsub(swap,"@2@2" .. swap .. "@2@2", nooftimes)) 
     a_string = (a_string:gsub(swapwith,"@3@3" .. swapwith .. "@3@3", nooftimes))
     a_string = (a_string:gsub("@3@3" .. swapwith .. "@3@3", swap, nooftimes))
     a_string = (a_string:gsub("@2@2" .. swap .. "@2@2", swapwith, nooftimes))

  return a_string

end


return p