# How can i choose two keys from a table?

how can i choose two keys from a table?
I’m trying to make a map voting system but I need to choose two maps to vote from a table and then change the ui.

Here’s a code, which can choose two random keys from the table:

``````local myTableWithKeys = {
["One"] = 1,
["Two"] = 2,
["Three"] = 3,
["Four"] = 4,
["Five"] = 5
}
local tableWithJustKeys = {}
local twoRandomKeys = {}

for key, value in pairs(myTableWithKeys) do
table.insert(tableWithJustKeys, key)
end
for i = 1, 2 do
local randomNumber = math.random(1, #tableWithJustKeys)
table.insert(twoRandomKeys, tableWithJustKeys[randomNumber])
table.remove(tableWithJustKeys, randomNumber)
end

print("These are two random keys:")
for index, value in pairs(twoRandomKeys) do
print(value)
end
``````
1 Like
``````function getKeys(t: {[any]: any}): {any}
local keys = {}
for key, _ in pairs(t) do table.insert(keys, key) end
return keys
end

function pickRandomKeys(t: {[any]: any}, num: number): {any}
local keys = getKeys(t)
local chosen = {}
for i = 1, math.min(num, #keys) do
local index = math.random(1, #keys)
table.insert(chosen, keys[index])
table.remove(keys, index)
end
return chosen
end

local dict = {One = 1, Two = 2, Three = 3, Four = 4, Five = 5}

print(pickRandomKeys(dict, 2)) --{randomKey1, randomKey2}
``````
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.