lua-users home
lua-l archive

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


> Is there any way I can preserve the order of items in a table?
> 
> For example, if I do:
> 
>     tbl = { a=1, b=2, c=3 }
>     for i,v in tbl do
>         print(i,v)
>     end
> 
> Then I get:
> 
> a       1
> c       3
> b       2
> 
> Note I do not want the table alpha (or otherwise) sorted; I 
> need to be able to get back the items in the same order as 
> they were added when tbl was initialised.

Unfortunately, there is no built-in way to do this is the hashed system
of Lua tables.  A possible way to handle this, though, would be to:

function table_add(table, key, value)
	table[getn(table) + 1] = key
	table[key] = value
end

function table_iterate(table, func)
	for index = 1, getn(table) do
		func(table[index], table[table[index]])
	end
end

tbl = {}
table_add(tbl, 'a', 1)
table_add(tbl, 'b', 2)
table_add(tbl, 'c', 3)

table_iterate(tbl, function(key, value) print(key, value) end)

To be able to set up a tag method for this, though, to make it more
natural, would require Edgar's idea of a newindex tag (I believe).
Plus, there is no way to replace the iteration for a for loop... That
would be cool, though.

Josh