Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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} 
like image 299
ewok Avatar asked Oct 01 '12 13:10

ewok


People also ask

How do I get the key of a value in Lua?

To access the value associated with the key in a table you can use the table[key] syntax: > t = {} > t["foo"] = 123 -- assign the value 123 to the key "foo" in the table > t[3] = "bar" -- assign the value "bar" to the key 3 in the table > = t["foo"] 123 > = t[3] bar.

How do I index a table in Lua?

For Lua, that means "index the table io using the string "read" as the key". When a program has no references to a table left, Lua memory management will eventually delete the table and reuse its memory. Notice the last line: Like global variables, table fields evaluate to nil if they are not initialized.

Are Lua tables hash tables?

We all know that a Lua table is a hash table, which uses a hash function to map a key into one of the table's slots. However, the result of the hash function is not unique. There exist some keys that have the same hash value, i.e., it may map some different keys into the same slot.

Is everything in Lua a table?

Tables are a versatile data structure that can be used as arrays, dictionaries, objects, etc. However, Lua provides many types besides tables: numbers, booleans, closures (functions), strings (which are interned), coroutines, and something called userdata (which are typically pointers to something implemented in C).


2 Answers

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

like image 107
lhf Avatar answered Sep 18 '22 03:09

lhf


local function get_keys(t)   local keys={}   for key,_ in pairs(t) do     table.insert(keys, key)   end   return keys end 
like image 22
Paul Hilliar Avatar answered Sep 18 '22 03:09

Paul Hilliar