[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: lua table order?
- From: Petite Abeille <petite.abeille@...>
- Date: Mon, 5 Apr 2010 23:15:59 +0200
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