From: Jo-Philipp Wich Date: Sun, 8 Jun 2008 20:51:48 +0000 (+0000) Subject: * luci/core: add spairs(), kspairs() and vspairs() sorted hashtable iterator functions X-Git-Tag: 0.8.0~850 X-Git-Url: https://git.librecmc.org/?a=commitdiff_plain;h=4ad4a77b3da1f04fa6ce5421d843e2da57a8f4ea;p=oweals%2Fluci.git * luci/core: add spairs(), kspairs() and vspairs() sorted hashtable iterator functions --- diff --git a/libs/core/luasrc/util.lua b/libs/core/luasrc/util.lua index 11f77206b..ad53138e6 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