How can I get a random attribute?

Greetings!

We know how to get a random instance, right?

local function GetInstance(Folder)
	local InstanceArray = InstanceArray:GetChildren()
	local RandomInstance = InstanceArray[math.random(1, #InstanceArray)]
	return RandomInstance
end

However, I tried the same method, but to get a random Attribute.

local function GetAttribute(Folder)
	local Attributes = Folder:GetAttributes()
	local RandomAttribute = Attributes[math.random(1, #Attributes)]
	return RandomAttribute
end

And it just ends up coming up with this error:


If you can help me, that would be great!

I know that each attribute needs to be 1, 2, 3, etc…
image

Thanks in advance!

Sincerely, Will

The attribute name is cast to a string so the “1” is actually a string and not a number so #Attributes will always return 0. You can loop through the attributes and add them to a numerical index array.

GetAttributes returns a dictionary, not an array. The # operator can only be used on arrays. This means that it will return a value of 0, because Attributes is a dictionary. To get the number of items in a dictionary, loop through it with a counter variable.

Can you show me how to get a random one in a dictionary with a script example? Not really catching what you mean. I’m a visual learner.

local Attributes = Folder:GetAttributes()
local AttributesArray = {}

for i, v in pairs(Attributes) do
    table.insert(AttributesArray, v)
end

print(AttributesArray[math.random(#AttributesArray)])
2 Likes

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