How do I get a random value in this type of table?

I’m not sure what this type of table is, but

TheTable = {
	
	["House"] = {
		["Chance"] = 10,
		["Money"] = 1
	},

	["Cool"] = {
		["Chance"] = 1.2,
		["Money"] = 1
	},
	
	["Flame"] = {
		["Chance"] = 1.2,
		["Money"] = 1
	},
	
	["thing"] = {
		["Chance"] = 10,
		["Money"] = 1
	},
	
	["Unknown"] = {
		["Chance"] = 7,
		["Money"] = 1
	},
	
	["Random"] = {
		["Chance"] = 25,
		["Money"] = 1
	},
	
	["Shade"] = {
		["Chance"] = 90,
		["Money"] = 1
	},
	
	["Joseph"] = {
		["Chance"] = 85,
		["Money"] = 1
	},
	
}

local randomValue = TheTable[math.random(1, #TheTable)]

print(randomValue.Chance)

This is my current code. Doesn’t work, says it attempt to index nil with number. How would I get a random value?

Any help would be VERY appreciated.
Another thing, does anyone know what this type of table is called?

This is a dictionary-like array (a dictionary). And its members must be indexed by their keys. Using # on a dictionary will return 0, since it’s not a table and it uses keys instead of default number indexes.

If you want to get a random member inside a dictionary, you can create a function that will loop through the members, insert the names of those members into a table, then get a random name from that table, which would be a key inside a dictionary.

local fruits = {
    ["Apples"] = 60,
    ["Oranges"] = 54,
    ["Bananas"] = 67
}

local function getRandomKey(dictionary: {})
    local keys = {}

    for key, _ in dictionary do
        table.insert(keys, key)
    end

    return dictionary[keys[math.random(#keys)]]
end

-- If the key was "Apple", this variable will hold 60.
local randomFruitCount = getRandomKey(fruits)
1 Like

This type of table is called a dictionary. Instead of numerical increasing keys like arrays, this one has string keys you define in its structure(like Joseph for example). There’s currently no way to get the length of a dictionary except by iterating through it. I assume a good solution is to iterate through the table, only store the keys in another array and then pick a random key to index the dictionary(that way you also don’t have to store the contents of each key twice, so it’s useful for larger dictionaries as well):

local keys = {}
for key, _ in pairs(TheTable) do table.insert(keys, key) end
local key = keys[math.random(1, #keys)]
local value = TheTable[key]
print(key, value)

Also lol @Ovibion we thought the same thing.

2 Likes

Well, great minds think alike. xD

1 Like

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