【问题标题】:Lua - decodeURI (luvit)Lua - decodeURI (luvit)
【发布时间】:2013-12-05 16:55:34
【问题描述】:

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

JavaScript:

decodeURI('%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82')
// result: привет

卢维特:

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'

【问题讨论】:

标签: lua urldecode encodeuricomponent decodeuricomponent


【解决方案1】:

如果你理解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'))

【讨论】:

  • 你可以使用%%(%x%x)作为模式。
【解决方案2】:

这是另一个镜头。如果您必须解码许多字符串,此代码将为您节省大量函数调用。

local hex = {}
for i = 0, 255 do
    hex[string.format("%02x", i)] = string.char(i)
    hex[string.format("%02X", 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'))

【讨论】:

  • 有趣。您将所有可能的百分比编码的十六进制八位字节(大写和小写)缓存到查找表中以供gsub 使用。我唯一注意到的是在极端情况下你可能会得到一个混合大小写的八位字节,例如Fe,但我怀疑这在实践中会发生。
  • 代码不适用于前 16 个字符 hex[string.format("%02x",i)]=string.char(i) 在 x 前添加 2
【解决方案3】:

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!"

【讨论】:

    猜你喜欢
    • 2012-01-10
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多