lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I have this code (pared down):

  local function sortElementsByTabIndex( inEl1, inEl2 )
    output( 'comparing '..tostring(inEl1)..' with '..tostring(inEl2) )
    return this_lib.focusable[ inEl1 ] < this_lib.focusable[ inEl2 ]
  end

  local __tabElements = {}
  function updateFocusableTabIndices( self )
    -- push all elements into the array
    local i = 1
    for --stuff-- do
      __tabElements[ i ] = theElement
      i = i + 1
    end

    -- mark the end of the array
    __tabElements.n    = i-1
    __tabElements[ i ] = nil
  
    if i > 2 then
      -- sort the array by tab index
      output( 'going to sort '..(i-1)..' items:' )
      for x,v in ipairs( __tabElements) do
        output( 'item #'..x..' is '..tostring(v) )
      end
      table.sort( __tabElements, sortElementsByTabIndex )
      output( 'done sorting!' )
    
      -- Update all the indices for reverse lookup
      for i,theElement in ipairs( __tabElements ) do
        __tabElements[ theElement ] = i
      end
    end
  end

It works fine on the first pass, but on the second pass here's the
output:
  going to sort 4 items:
  item #1 is userdata: 00F072F0
  item #2 is userdata: 00F078F4
  item #3 is userdata: 00F06CEC
  item #4 is userdata: 00F066E8
  comparing userdata: 00F08FFC with userdata: 00F072F0
  comparing userdata: 00F072F0 with userdata: 00F072F0
  comparing userdata: 00F08FFC with userdata: 00F072F0
  comparing userdata: 00F078F4 with userdata: 00F072F0
  comparing userdata: 00F072F0 with userdata: 00F080C4
  comparing userdata: 00F072F0 with userdata: 00F078F4
  comparing userdata: 00F072F0 with userdata: 00F078F4
  comparing userdata: 00F072F0 with userdata: 00F08860
  comparing userdata: 00F072F0 with nil

Given the presence of 00F08860 getting passed to my comparison function,
it seems that table.sort tries to sort all the integer keys in the
array, instead of the convential "from 1 up to the first nil" view of an
array.

Is this behavior expected? Do I need to wipe out all the subsequent
values, instead of just inserting a nil marker?

Do I need to also worry about the non-integer keys in the table? (The
reverse-lookup elements pushed in at the end.)