0 Replies - 1043 Views - Last Post: 21 July 2010 - 11:33 AM

#1 athlon32  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 117
  • View blog
  • Posts: 363
  • Joined: 20-August 08

[LUA]Sparse Array Iterator

Posted 21 July 2010 - 11:33 AM

Description: Please note that the function 'table.maxn' takes linear time, rendering this slightly slower than a normal iterator. For this reason, reserve it only for sparse arrays!In Lua, a sparse array is a table in which there are spaces between consecutive indexes that contain values; that is, elements are held more or less in random locations. Normal iterators traverse a table until a 'nil' item is found. This won't work with sparse arrays. Instead, this custom iterator works by getting the true length of a table, and by using a closure, it can assure every element is visited.
require "table";

function sparse(t)
    local length = table.maxn(t); -- unfortunately, the # operator doesn't apply
    local i = 0;
    return function() 
               if i < length then
                   i = i+1;
                   return i, t[i];
               else 
                   return nil;
               end
           end
end


-- Note: this array has approximately 998 nil indexes.  
local t = { [1] = 4, [6] = 75, [1002] = 56, [532] = 9 };

for i, v in sparse(t) do
    -- ignore the nils
    if v then  
        print(i, v);
    end
end


Is This A Good Question/Topic? 0
  • +

Page 1 of 1