How to keep the order of a Lua table with string keys?

steven picture steven · Oct 9, 2013 · Viewed 11.3k times · Source

Here's an example

local query = {}
query['count'] = 1
query['query'] = 2
for k,v in pairs(query) do
    print(k)
end

The above will print first query then count.

How can I make sure without adding an int index key that the key strings keep their order when I loop through the table?

Answer

Josh picture Josh · Oct 9, 2013

I answered in comment, but I'm moving it here to give a better idea of what I'm talking about.

local queryindex = {"count", "query"}
local query = {}
query['count'] = 1
query['query'] = 2

for _,v in ipairs(queryindex) do
  print(query[v])
end