Get all keys from table

This is a dumb question, but Google isn’t giving me anything.

If I have a table like this:



t = {'a' = 1, 'b' = 2, ... }


How do I get the keys?

Specifically, I need to select one of the pairs from the table at random, which is tricky since nothing is indexed by an integer.

Hmm I guess you could try something like that :

[lua]function RandomKey(Table)
local temp = {}
for k,v in pairs(Table) do
table.insert(Table,k)
end
return Table[table.Random(temp)]
end[/lua]

This probably isn’t the best way, or even a smart way, but here you go. :slight_smile:

If you’re just looking to choose a random item, I’m pretty sure you can just use table.Random, like in Quebec’s code. It shouldn’t matter with or without integer keys.

The problem with table.Random, though, is that it only returns a value without its key. I need to grab both the key and the value.

I suppose what I could do instead is have a list of lists instead of a dictionary, like this:
[lua]
t = {{‘a’, 1}, {‘b’, 2}, …}
[/lua]

Then table.Random could get me the pairs I need.

[lua]
function table.RandomKV(t, size)
if not size then
size = 0
local k, v = next(t)
while k do
size = size+1
k, v = next(t, k)
end
end
local k, v = nil
for i = 1, math.random(size) do
local k, v = next(t, k)
end
return next(k), size
end
[/lua]

If you already know the size of the table, just pass it (Can be acquired via table.Count).

[lua]function RandomKey(Table)
local temp = {}
for k,v in pairs(Table) do
table.insert(temp,k)
end
local key = table.Random(temp)
return key,Table[key]
end[/lua]
This will return a random key/value pair.