lua-users home
lua-l archive

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


>How does Lua handle sorting in tables where indexing values are non-numeric?

sort only works on integer indices. The manual says

   sort (table [, comp])

   Sorts table elements in a given order, in-place, from table[1] to
   table[n], where n is the result of getn(table) (see Section 6.1).

>I need a fixed behavior so my program wont display different sortings to the users.

You mean, you need to traverse a table in alphabetical order or indices?
If so, here's a solution.

You have to collect the indices into a table, sort it, and them use it index
the original table. Something like

do
 local I={n=0}
 foreach(t,function (i,v) tinsert(%I,i) end)
 sort(I)
 foreachi(I,function (i,v) process(t[v]) end)
end

--lhf