2

I need to iterate through Lua table in order which it's created. I found this article - http://lua-users.org/wiki/SortedIteration But it doesn't seems like working:

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.

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

if key then
    return key, t[key]
end

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

function orderedPairs(t)
    return orderedNext, t, nil
end

Here is the usage example:

t = {
['a'] = 'xxx',
['b'] = 'xxx',
['c'] = 'xxx',
['d'] = 'xxx',
['e'] = 'xxx',
}


for key, val in orderedPairs(t) do
   print(key.." : "..val)
end

I'm getting an error:

attempt to call field 'getn' (a nil value)

What is the problem?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Alex Smoke
  • 619
  • 1
  • 8
  • 18

1 Answers1

4

table.getn has been removed since Lua 5.1, it's replaced by the # operator.

Change table.getn(t.__orderedIndex) to #t.__orderedIndex.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • And what if I need to iterate in order in which it's created. Is it possible? – Alex Smoke Sep 07 '15 at 15:28
  • 3
    The order is unspecified. Ask a new question if you've got a new one. – Yu Hao Sep 07 '15 at 15:30
  • Thank you very much, new question is here - http://stackoverflow.com/questions/32451755/is-there-a-way-to-iterate-through-lua-dictionary-in-order-that-its-created . Would really appreciate your help. – Alex Smoke Sep 08 '15 at 07:38