Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Here’s my bit of public domain code for iterating through tables in Lua so that the elements are sorted. This routine works like the pairs() function included with Lua:

  -- Like pairs() but sorted
  function sPairs(inTable, sFunc)
    if not sFunc then
      sFunc = function(a, b)
        local ta = type(a)
        local tb = type(b)
        if(ta == tb)
          then return a < b 
        end
        return ta < tb
      end
    end
    local keyList = {}
    local index = 1
    for k,_ in pairs(inTable) do
      table.insert(keyList,k)
    end
    table.sort(keyList, sFunc)
    return function()
      key = keyList[index]
      index = index + 1
      return key, inTable[key]
    end
  end
Example usage of the above function:

  a={z=1,y=2,c=3,w=4}
  for k,v in sPairs(a) do
    print(k,v)
  end
With a sort function:

  a={z=1,y=2,c=3,w=4}
  function revS(a,b)
    return a>b
  end
  for k,v in sPairs(a,revS) do
    print(k,v)
  end
(Yes, this is a lot easier to do in Perl or Python, since those languages unlike Lua have built in list iterators, but it’s possible to do in Lua too)


If you did not return a closure, you could set the metatables __pairs to use your function's. Sadly, you could not do this without keeping some sort of cache, which would be a terrible waste of memory, but then again you're already creating an iterator that iterates completely, to me, this beats the use of an iterator (to not iterate over everything and break on a single pass)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: