ewok
ewok

Reputation: 21443

lua: retrieve list of keys in a table

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}

Upvotes: 61

Views: 108011

Answers (2)

Paul Hilliar
Paul Hilliar

Reputation: 738

local function get_keys(t)
  local keys={}
  for key,_ in pairs(t) do
    table.insert(keys, key)
  end
  return keys
end

Upvotes: 8

lhf
lhf

Reputation: 72312

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).

Upvotes: 63

Related Questions