lua: retrieve list of keys in a table

ewok picture ewok · Oct 1, 2012 · Viewed 56.5k times · Source

I need to know how to retrieve the key set of a table in lua. for example, if I have the following table:

tab = {}
tab[1]='a'
tab[2]='b'
tab[5]='e'

I want to be retrieve a table that looks like the following:

keyset = {1,2,5}

Answer

lhf picture lhf · Oct 1, 2012
local keyset={}
local n=0

for k,v in pairs(tab) do
  n=n+1
  keyset[n]=k
end

Note that you cannot guarantee any order in keyset. If you want the keys in sorted order, then sort keyset with table.sort(keyset).