lua-users home
lua-l archive

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


I believe that Lua tables have no implied ordering. It is certainly not
guaranteed that iterating a table with pairs will return items in the
same order they were added.

For tables used as arrays, with 1-based integer keys, the table can be
iterated in order by using ipairs. I cant see this working with your
dataset since you have a mixture of named and unnamed fields. You might
want to check out http://www.lua.org/pil/19.3.html, which explains how
to sort a table much more clearly than I can.

One way to retrieve data in a guaranteed order would be to write
functions tailored to your data rather than generic iteration code.
Something like:

function printServer(s)
	print (s.server)
	print (s.IP)
	print (s[1].domain)	-- the anonymous table will end up with
key 1
	print (s[1].class)
	-- and so on
end

function Project(t)
{
	print (t.name)

	-- all the anonymous tables in the data will be entered under
consecutive integer keys
	-- ipairs will preserve their ordering.
	for i, v in ipairs(table) do
		printServer(v)
	end
}

I recognise that this means the output functions need to be tailored to
the data format, but it does give precise control over the order of
output. I see no easy way to write generic code to do this. Generic code
to output the string keys and data in alphabetic order is easy, but I
don't think this is what you want either.

- DC