lua-users home
lua-l archive

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


Personally, the pattern I usually do when I'm designing around this is to create a table of tables with the desired key in the first spot and the desired value in the second, such as

local kvpairs ={
  {'one', 989},
  {'two', 'zeze'},
  {'three', 78},
  {'four', 'joseepti'},
  {'five', os.date('!%a,  > %d-%b-%Y %H:%M:%S GMT')}
}

-- followed by something like --

local tb={ k={}, i={} }

for i, kv in ipairs(kvpairs) do
  local k, v = unpack(kv) -- or skip this and use kv[1] and kv[2]
  tb.k[k] = v
  tb.i[i] = v
end

-- Then, if I need to index by position (or use an array function), I use tb.i, and if I need to index by the arbitrary key, I use tb.k.

On Mon, 05 Apr 2010 15:15:59 -0600, Petite Abeille <petite.abeille@gmail.com> wrote:


On Apr 5, 2010, at 10:41 PM, Luiz Henrique de Figueiredo wrote:

i expected an output order, but it fails ...

"The order in which the indices are enumerated is not specified"
http://www.lua.org/manual/5.1/manual.html#pdf-next

And if you want to order your table, you need to sort it somehow, e.g. alphabetically by keys:

local function Sort( aMap )
    local aList = {}
    local anIndex = 1
   for aKey, aValue in pairs( aMap ) do
        aList[ #aList + 1 ] = aKey
    end
   table.sort( aList )
   return function()
        local aKey = aList[ anIndex ]
        local aValue = aMap[ aKey ]
       anIndex = anIndex + 1
       return aKey, aValue
    end
end


local tb={['one']=989,['two']='zeze',['tree']=78,['four']='joseepti',['five']=os.date('!%a, %d-%b-%Y %H:%M:%S GMT')}

for aKey, aValue in Sort( tb ) do
    print( aKey, aValue )
end

five	Mon, 05-Apr-2010 00:07:07 GMT
four	joseepti
one	989
tree	78
two	zeze

Check the wiki for alternatives:

http://lua-users.org/wiki/OrderedTable