Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

lua

lua-table

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?

like image 617
steven Avatar asked Oct 08 '13 23:10

steven


1 Answers

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
like image 98
Josh Avatar answered Sep 28 '22 08:09

Josh