Skip to content

Instantly share code, notes, and snippets.

@sharonovd
Created November 23, 2018 10:31
Show Gist options
  • Save sharonovd/6e6c9120126e01727bdf3e79ddeccc37 to your computer and use it in GitHub Desktop.
Save sharonovd/6e6c9120126e01727bdf3e79ddeccc37 to your computer and use it in GitHub Desktop.
urlencode
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