URL encoding is an encoding used by HTTP to pass various parameters in a single URL. This encoding encodes the special characters ("=", "&", "+") into the form "%<xx>".
<xx> is the hexadecimal representation of the character. In addition, it converts the space to "+", for example, it encodes the string "a+b = C" as: "A%2bb+%3d+c"
Finally, it joins each pair of parameter names and their values with "=" and joins each pair of result name = value with "&", for example, for values:
Name="al""a+b = C"; q="Yes or no"
will be encoded as:
" Name=al&query=a%2bb+%3d+c&q=yes+or+no " "+" Here is the space
Now, you want to decode this URL. Requires that each value in the encoding be saved in a table with its name as key:
functionUnescape (s) s=string.gsub(S,"+"," ")--convert + to spaces =string.gsub(S,"Percent (%x%x)",function(h)--convert%xx to the appropriate character return String.char(Tonumber(H, -)) End) returnsEndPrint(Unescape ("A%2bb+%3d+c"))-->a+b = C
Use Gmatch to decode name = value. Because both the name and the value cannot contain "&" and "=", you can use the pattern "[^&=]+" to match them:
cgi = {}function decode (s) for instring.gmatch(S," ([^&=]+) = ([^&=]+)" do = usecape (name) = unescape (value) = value endEnd
For each set of parameters, the iterator takes the captured content as the value of the variable name and value. The loop body simply calls Unescape on two strings, and then saves the result in the CGI table.
On the other hand, coding functions are also easy to write. First, write an escape function: Encode all special characters as "%" and accompany the hexadecimal code of that character. Convert a space to a "+"
functionEscape (s) s=string.gsub(S,"[&=+%%%c]",function(c)--match the "&", "=", "+", "%", and "%c" controls, and use function to convert it to%xx form. return String.Format("%%%02x",String.byte(c))-- End) s=string.gsub(S," ","+")--convert space to "+" returnsEnd
The ENCODE function traverses the entire table to be encoded, building the final result string:
functionencode (t)Localb = {} forKvinch Pairs(t) Dob[#b +1] = (Escape (k):"=".: Escape (v))End return Table.concat(b,"&")EndT= {Name ="Al", query ="a+b = C", q ="Yes or no"}Print(Encode (t))-->q=yes+or+no&query=a%2bb+%3d+c&name=al
The above: The second edition of LUA programming and the programming in Lua Third edition
Chapter 21_5.1 URL encoding