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}
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.
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.
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.
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).
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)
.
local function get_keys(t) local keys={} for key,_ in pairs(t) do table.insert(keys, key) end return keys end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With