I want to pick a random table inside a table. How do I make that?

So basically I want be able to pick a random table inside a table that has multiple other table and then print it but the output only prints nil

Here is the script

local Countries = {

}
Countries["Canada"] = {
	Country_Name = "Canada",
	Country_Image = "rbxassetid://12769829105",
	Country_Size = UDim2.new(0.225, 0,0.166, 0) ,
	Country_Fact = "Test lol",
}


Countries["USA"] = {
	Country_Name = "United States of America",
	Country_Image = "rbxassetid://12770252742",
	Country_Size = UDim2.new(0.225, 0,0.2, 0) ,
	Country_Fact = "Fun fact: ",
}

Countries["Russia"] = {
	Country_Name = "Russia",
	Country_Image = "rbxassetid://12770348182",
	Country_Size = UDim2.new(0.19, 0,0.2, 0) ,
	Country_Fact = "Fun fact: ",
}


wait(5)
local choice_1 = Countries[math.random(0,#Countries)] --Those are the two important lines that I'm not so sure how to code that
print(choice_1)

Can anyone help me on how I could make what I want?

1 Like

You’d list all the indices of the dictionary inside of a separate table, then, get a random index from the newly created table.

--Example 
local t = {} -- example dictionary
t.Key = "value"
t.AnotherKey = "anotherValue"

local function getRandomValue(tb)
    local indices = {} -- a table that holds the indices in the provided table

    for index in tb do -- loop through the provided table 
       table.insert(indices, index) -- insert the index into the table that holds the indices
    end

    return tb[indices[math.random(#indices)]] 
    -- returns a random index in tb using the indices table
    --[[ 
       the same as:
            local randomIndex = indices[math.random(#indices)]
            local value = tb[randomIndex]
    --]]
end

print(getRandomValue(t)) -- prints a random value in the dictionary 
1 Like

What if I want to choose a value inside a table that the script randomly chose? Is that possible? (thank you for helping me btw)

Yea, you would just index it:

local randomCountry = getRandomValue(Countries)
print(randomCountry.Country_Name)
1 Like

Thank you for your help problem! I really appreciate it!

1 Like

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