orderedtable.lua

main 43 lines · 1.2 KB Raw
Alex Alex Commit Client Upload Part 2 19/10/2026 00:06
1function __genOrderedIndex( t )
2 local orderedIndex = {}
3 for key in pairs(t) do
4 table.insert( orderedIndex, key )
5 end
6 table.sort( orderedIndex )
7 return orderedIndex
8end
9
10function orderedNext(t, state)
11 -- Equivalent of the next function, but returns the keys in the alphabetic
12 -- order. We use a temporary ordered key table that is stored in the
13 -- table being iterated.
14
15 local key = nil
16 --print("orderedNext: state = "..tostring(state) )
17 if state == nil then
18 -- the first time, generate the index
19 t.__orderedIndex = __genOrderedIndex( t )
20 key = t.__orderedIndex[1]
21 else
22 -- fetch the next value
23 for i = 1,table.getn(t.__orderedIndex) do
24 if t.__orderedIndex[i] == state then
25 key = t.__orderedIndex[i+1]
26 end
27 end
28 end
29
30 if key then
31 return key, t[key]
32 end
33
34 -- no more value to return, cleanup
35 t.__orderedIndex = nil
36 return
37end
38
39function orderedPairs(t)
40 -- Equivalent of the pairs() function on tables. Allows to iterate
41 -- in order
42 return orderedNext, t, nil
43end
Top