the reason
ipairs doesn't work is because it is designed to work with indexes (hence the i) using strings is referred to as keys.
now I'm sure as you know there is no order guaranteed with the
pairs function either. so what is the solution then? well you're going to have to implement your own 'pairs' like function; I propose the following code
local function orderedPairs( _t )
local keys = {} --# lets make a list of all the keys, and only the keys, they will be stored numbered!
for k in pairs(_t) do
table.insert(keys, k) --# insert the keys into the table
end
table.sort(keys) --# this is the important line! this puts the keys in order
local index = 0 --# this is the index we're currently accessing
return function()
index = index + 1 --# increment the index
local key = keys[index] --# get the key
return key, _t[key] --# return the key and the value from the original table
end
end
and with the usage of
for k,v in orderedPairs(testtab) do
print(k, ' : ', v)
end
Quick side note: It has been previously discussed and we have all come to the conclusion that you're better to use a standard for loop over
ipairs, it adds no extra benefit, it actually slows it down, by using
ipairs.
Edited by theoriginalbit, 12 March 2014 - 09:30 AM.