Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - decodeURI (luvit)

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

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'
like image 636
Kosmetika Avatar asked Dec 05 '13 16:12

Kosmetika


1 Answers

This is trivial to do yourself in Lua if you understand the URI percent-encoded format. Each %XX substring represents UTF-8 data encoded with a % 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'))
like image 171
Ryan Stein Avatar answered Nov 01 '22 18:11

Ryan Stein