Created
November 23, 2018 10:31
-
-
Save sharonovd/6e6c9120126e01727bdf3e79ddeccc37 to your computer and use it in GitHub Desktop.
urlencode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function utils.urlencode(data) | |
if type(data) == 'string' then | |
if data then | |
local res = string.gsub(data, '\n', '\r\n') | |
res = string.gsub(res, '([^%w _.~-])', function(c) | |
return string.format('%%%02X', string.byte(c)) | |
end) | |
return string.gsub(res, ' ', '+') | |
end | |
elseif type(data) == 'number' then | |
return tostring(data) | |
elseif type(data) == 'table' then | |
local res = '' | |
for k, v in pairs(data) do | |
local template = res:len() == 0 and '%s=%s' or '&%s=%s' | |
res = res .. template:format(utils.urlencode(k), | |
utils.urlencode(v)) | |
end | |
return res | |
else | |
error('unsupported type of data for utils.urlencode: ' .. type(data)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment