谷歌拼音扩展 LUA 中的 orderedPairs

今天在写谷歌拼音扩展,希望给出的候选词能按照数字顺序排列,而我在源文件中 tablekey 已经按顺序写了,可输出仍然是乱序。于是去官网查了点资料,发现一段代码:

--[[
Ordered table iterator, allow to iterate on the natural order of the keys of a
table.

Example:
]]

function __genOrderedIndex( t )
    local orderedIndex = {}
    for key in pairs(t) do
        table.insert( orderedIndex, key )
    end
    table.sort( orderedIndex )
    return orderedIndex
end

function orderedNext(t, state)
    -- Equivalent of the next function, but returns the keys in the alphabetic
    -- order. We use a temporary ordered key table that is stored in the
    -- table being iterated.

    --print("orderedNext: state = "..tostring(state) )
    if state == nil then
        -- the first time, generate the index
        t.__orderedIndex = __genOrderedIndex( t )
        key = t.__orderedIndex[1]
        return key, t[key]
    end
    -- fetch the next value
    key = nil
    for i = 1,table.getn(t.__orderedIndex) do
        if t.__orderedIndex[i] == state then
            key = t.__orderedIndex[i+1]
        end
    end

    if key then
        return key, t[key]
    end

    -- no more value to return, cleanup
    t.__orderedIndex = nil
    return
end

function orderedPairs(t)
    -- Equivalent of the pairs() function on tables. Allows to iterate
    -- in order
    return orderedNext, t, nil
end

只需要用 orderedPairs() 代替掉 pairs() 即可,但是后来发现我的扩展中若嵌入这么大一段代码,大小就太大了,于是就打算精简下。联想到 .Net 程序的混淆器,我如法炮制,将所有变量名全部混淆,于是得到了下面的代码:

_0=pairs function _1(_6)local _2={}for _4 in _0(_6)do table.insert(_2,_4)end table.sort(_2)return _2 end function _3(_6,_5)if _5==nil then _6._7=_1(_6)_4=_6._7[1]return _4,_6[_4]end _4=nil for _8 = 1,table.getn(_6._7)do if _6._7[_8]==_5 then _4=_6._7[_8+1]end end if _4 then return _4,_6[_4]end _6._7=nil return end function _9(_6)return _3,_6,nil end pairs=_9

嗯,你应该看出来了我直接将 pairsorderedPairs(这里其实是 _9)覆盖了。

总之,这个对于平常的开发是无用的,但是对于谷歌拼音扩展则是十分有用。你要是喜欢,欢迎随便转载。我已经提交到官方 wiki 去了。

| This entry was posted in E = Effective Computers and tagged , , , , . Bookmark the permalink.

One Response to 谷歌拼音扩展 LUA 中的 orderedPairs

  1. orzFly says:

    杯具唉……

    技术文果然没啥看点。

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>