In Lua, only tables with 1-based consecutive integer keys (a.k.a. array tables) can be parsed in order.
So, if you want to parse a table t
in order, what you do is:
- collecting its keys into an array-like table
- sorting that
keys
table
- using the
keys
table to iterate over t
.
Example:
function sortedKeys(query, sortFunction)
local keys, len = {}, 0
for k,_ in pairs(query) do
len = len + 1
keys[len] = k
end
table.sort(keys, sortFunction)
return keys
end
...
local query = {}
query['count'] = 1
query['query'] = 2
for _,k in pairs(sortedKeys(query)) do
print(k, query[k])
end
It's also possible to create an iterator to do this a bit more idiomatically, but I never had the need.