Advertisement
xrobau

Lua URI Encode Function

Aug 15th, 2019
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.91 KB | None | 0 0
  1. -- Lua uriencode function
  2. -- Can take a table, or a string of comma separated values.
  3. -- Examples:
  4. -- > print(uriencode("this=is,a=/test/,string='quotes'"))
  5. -- a=%2Ftest%2F&string=%27quotes%27&this=is
  6. -- > print(uriencode({this="is", a="/test/", string="'quotes'"}))
  7. -- a=%2Ftest%2F&string=%27quotes%27&this=is
  8. function uriencode(vals)
  9.     function escape (s)
  10.         s = string.gsub(
  11.             s,
  12.             '([\r\n"#%%&+:;<=>?@^`{|}%\\%[%]%(%)$!~,/\'])',
  13.             function (c)
  14.                 return '%'..string.format("%02X", string.byte(c));
  15.             end
  16.         );
  17.         s = string.gsub(s, "%s", "+");
  18.         return s;
  19.     end
  20.     function encode (t)
  21.         local s = "";
  22.         for k , v in pairs(t) do
  23.             s = s .. "&" .. escape(k) .. "=" .. escape(v);
  24.         end
  25.         return string.sub(s, 2);
  26.     end
  27.     if type(vals) == 'table' then
  28.         return encode(vals);
  29.     else
  30.         local t = {};
  31.         for k, v in  string.gmatch(vals, ",?([^=]+)=([^,]+)") do
  32.             t[k]=v;
  33.         end
  34.         return encode(t);
  35.     end
  36. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement