Lua - decodeURI(luvit)

时间:2013-12-05 16:55:35

标签: lua urldecode encodeuricomponent decodeuricomponent

我想在我的 Lua(Luvit)项目中使用JavaScript中的decodeURIdecodeURIComponent

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'

3 个答案:

答案 0 :(得分:11)

如果你理解URI percent-encoded format,那么在Lua做这件事是微不足道的。每个%XX子字符串表示使用%前缀和十六进制八位字节编码的UTF-8数据。

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'))

答案 1 :(得分:3)

这是另一种看法。如果你必须解码许多字符串,这段代码将为你节省大量的函数。

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'))

答案 2 :(得分:0)

URI用' '代表'+' 其他特殊字符用百分比表示,后跟2位十六进制字符代码'%0A',例如'\n'

local function decodeCharacter(code)
    -- get the number for the hex code 
    --   then get the character for that number
    return string.char(tonumber(code, 16))
end

function decodeURI(s)
    -- first replace '+' with ' '
    --   then, on the resulting string, decode % encoding
    local str = s:gsub("+", " ")
        :gsub('%%(%x%x)', decodeCharacter)
    return str 
    -- assignment to str removes the second return value of gsub
end

print(decodeURI('he%79+there%21')) -- prints "hey there!"