Skip to content

Instantly share code, notes, and snippets.

@cgwxyz
Last active June 23, 2020 14:09
Show Gist options
  • Save cgwxyz/6053d51e8d7134dd2e30 to your computer and use it in GitHub Desktop.
Save cgwxyz/6053d51e8d7134dd2e30 to your computer and use it in GitHub Desktop.
lua urlencode/urldecode
function encodeURI(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w ])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
function decodeURI(s)
if(s) then
s = string.gsub(s, '%%(%x%x)',
function (hex) return string.char(tonumber(hex,16)) end )
end
return s
end
@ltearno
Copy link

ltearno commented Mar 22, 2018

You should add this line at line 13 :

s = string.gsub(s, "+", " ")

@DanielVukelich
Copy link

Line 4 is not the right regex for url safe characters. This code will incorrectly % encode the characters . _ - ~ even though they are already safe per https://tools.ietf.org/html/rfc3986#section-2.3. The correct one would be

str = string.gsub(str, "([^%w _ %- . ~])",
    function (c) return string.format ("%%%02X", string.byte(c)) end)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment