LUA: urlencode and urldecode


function urlencode:

local function urlencode (str)
   str = string.gsub (str, "([^0-9a-zA-Z !'()*._~-])", -- locale independent
      function (c) return string.format ("%%%02X", string.byte(c)) end)
   str = string.gsub (str, " ", "+")
   return str
end

function urldecode:

local function urldecode (str)
   str = string.gsub (str, "+", " ")
   str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end)
   return str
end

Example:

print( urlencode("http://tutorialspots.com/") )

Result:

http%3A%2F%2Ftutorialspots.com%2F

Leave a Reply