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)
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)