Lua - decodeURI (luvit)

I would like to use decodeURI or decodeURIComponent , as in JavaScript in a Lua project (Luvit) .

JavaScript:

 decodeURI('%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82') // result:  

Luvit:

 require('querystring').urldecode('%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82') -- result: '%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82' 
+6
source share
2 answers

It is trivial to do yourself in Lua if you understand the URI encoded format . Each substring %XX represents UTF-8 data encoded with the % prefix and a hexadecimal octet.

 local decodeURI do local char, gsub, tonumber = string.char, string.gsub, tonumber local function _(hex) return char(tonumber(hex, 16)) end function decodeURI(s) s = gsub(s, '%%(%x%x)', _) return s end end print(decodeURI('%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82')) 
+10
source

Here is another take. This code will save you a lot of function calls if you need to decode many lines.

 local hex={} for i=0,255 do hex[string.format("%0x",i)]=string.char(i) hex[string.format("%0X",i)]=string.char(i) end local function decodeURI(s) return (s:gsub('%%(%x%x)',hex)) end print(decodeURI('%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82')) 
+3
source

Source: https://habr.com/ru/post/959406/


All Articles