diff options
author | Jo-Philipp Wich <jow@openwrt.org> | 2008-06-08 20:51:48 +0000 |
---|---|---|
committer | Jo-Philipp Wich <jow@openwrt.org> | 2008-06-08 20:51:48 +0000 |
commit | 4ad4a77b3da1f04fa6ce5421d843e2da57a8f4ea (patch) | |
tree | 528639efe824ec4290957943d7276a05d2127bab /libs/core | |
parent | ec1c9a6545a9b65b0fc9cb6264f2e401b06efa70 (diff) |
* luci/core: add spairs(), kspairs() and vspairs() sorted hashtable iterator functions
Diffstat (limited to 'libs/core')
-rw-r--r-- | libs/core/luasrc/util.lua | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/libs/core/luasrc/util.lua b/libs/core/luasrc/util.lua index 11f77206bc..ad53138e60 100644 --- a/libs/core/luasrc/util.lua +++ b/libs/core/luasrc/util.lua @@ -318,3 +318,40 @@ function parse_units(ustr) return val end + + +-- Provide various sorting iterators +function _sortiter( t, f ) + local keys = { } + + for k, v in pairs(t) do + table.insert( keys, k ) + end + + local _pos = 0 + local _len = table.getn( keys ) + + table.sort( keys, f ) + + return function() + _pos = _pos + 1 + if _pos <= _len then + return keys[_pos], t[keys[_pos]] + end + end +end + +-- Return key, value pairs sorted by provided callback function +function spairs(t,f) + return _sortiter( t, f ) +end + +-- Return key, value pairs sorted by keys +function kspairs(t) + return _sortiter( t ) +end + +-- Return key, value pairs sorted by values +function vspairs(t) + return _sortiter( t, function (a,b) return t[a] < t[b] end ) +end |