Hello. How do I make :GetAttributes() return an array instead of a dictionary? The reason why I want this is because table.find doesn’t work with dictionaries.
This is what :GetAttributes() returns:
What I want it to return:
Im guessing there is no way to get it to return an array, but how do I turn a dictionary into an array?
Its intended to be a dictionary for a reason, otherwise you wont know what value is which when using them.
If you’re focused on a few set values, create a new table, iterate through said dictionary, and put said values into the new table to be used as an array. But at that point, you’re pretty much better off making your own attribute system, it would be much more managable as it wouldn’t be worth your time to create seperate attributes for an array.
Why don’t you just loop through the dictionary though? There is no performance gain from removing the keys. All tables in lua are associative arrays.
Doing this:
for _, value in dictionary do
end
Is the exact same as:
for _, value in list do
end
If you want to get the index you can pass the table to the ipairs() function.
Fyi you can also overwrite the length operator to achieve the same result using only the dictionary but at that point it really depends on personal preference. Use whatever implementation you think suits you best. This solution has a time complexity of O(n) where n is the number of hashed values. If you need the length of the dictionary multiple times converting it into a sequence using the marked solution makes more sense as lua fetches the length of sequences with a time complexity of O(1) as far as I’m aware.
local t = {["hello"] = "world" }
local lengthmetatable = {}
lengthmetatable.__len = function(t)
local elements = 0
for _, val in pairs(t) do
elements += 1
end
return elements
end
setmetatable(t, lengthmetatable)
print(#t) --Prints 1