@@ -0,0 +1,76 @@
+---
+title: 谷歌拼音扩展 LUA 中的 orderedPairs
+author: orzFly
+layout: post
+permalink: /html/lua-orderedpairs.html
+btc_comment_counts:
+ - 'a:0:{}'
+btc_post:
+ - 'a:6:{s:2:"ID";s:3:"290";s:13:"post_date_gmt";s:19:"2010-02-11 16:00:37";s:23:"initial_import_date_gmt";s:19:"2010-03-22 21:57:11";s:20:"last_import_date_gmt";s:19:"2010-03-22 21:57:11";s:4:"hits";s:1:"0";s:6:"misses";s:1:"1";}'
+btc_comment_summary:
+ - 'a:0:{}'
+yourls_shorturl:
+ - http://miv.im/dbuh
+categories:
+ - Coding
+---
+今天在写<a href="http://orztech.com/google-pinyin-ime-extension/" target="_blank">谷歌拼音扩展</a>,希望给出的候选词能按照数字顺序排列,而我在源文件中 `table` 中 `key` 已经按顺序写了,可输出仍然是乱序。于是去<a href="http://lua-users.org/wiki/SortedIteration" rel="nofollow" target="_blank">官网</a>查了点资料,发现一段代码:
+
+<pre>--[[
+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</pre>
+
+只需要用 `orderedPairs()` 代替掉 `pairs()` 即可,但是后来发现我的扩展中若嵌入这么大一段代码,大小就太大了,于是就打算精简下。联想到 .Net 程序的混淆器,我如法炮制,将所有变量名全部混淆,于是得到了下面的代码:
+
+<pre>_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</pre>
+
+嗯,你应该看出来了我直接将 `pairs` 用 `orderedPairs`(这里其实是 `_9`)覆盖了。
+
+总之,这个对于平常的开发是无用的,但是对于谷歌拼音扩展则是十分有用。你要是喜欢,欢迎随便转载。我已经提交到<a href="http://lua-users.org/wiki/SortedIteration" rel="nofollow" target="_blank">官方 wiki</a> 去了。
\ No newline at end of file