I am currently working on a crate system on my game. I want to create a function that returns a random item within a table. The thing is that since I would just use the length of the table and return a random value. The problem is that you can’t get the length of the dictionary so how would I go about discerning the difference between the two inside of a script?
Using type and typeof both return ‘table’, regardless of whether it’s a dictionary or table.
I was planning on doing something closer to this, avoids the need of a count function.
ChooseRandomFromArray = function(self, array)
local indexes = {}
for i,v in pairs(array) do
indexes[#indexes + 1] = i
end
local chosenNumber = math.random(1, #indexes)
local chosenIndex = indexes[chosenNumber]
return array[chosenIndex]
end;
Yeah, you can index dictionaries. The problem I was facing is that you can’t get the length of dictionaries. Pairs goes through the entire dictionary whereas ipairs stops if there’s a numerical index missing.
Basically the only difference between a dictionary and a table is that tables’ indexes are always numeric whereas dictionaries have other indexes. Pretty much identical in terms of structure.
Just to answer OP’s question, the best way to distinguish between an array and a dictionary that I can think of would be to iterate over the given table and check the index’s type.
local function GetTableType(t)
assert(type(t) == "table", "Supplied argument is not a table")
for i,_ in pairs(t) do
if type(i) ~= "number" then
return "dictionary"
end
end
return "array"
end
local table1 = GetTableType({
[1] = "Test"
})
local table2 = GetTableType({
["1"] = "Test"
})
print(table1)
print(table2)
-- array
-- dictionary