Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Math.random for objects?

Asked by
Codebot 85
9 years ago

I'm trying to pick a random ImageButton from my gui. I get a bad argument because random is expecting a number and not an Object.

this = script.Parent

local btn = this.Buttons:GetChildren()
        for i = 1,#btn do
            b = math.random(1,btn[i])
            print(b)
        end
end
0
for some reason i think roblox updated that so it doesn't work anymore XD lomo0987 250 — 9y
0
@lomo0987 | ? What doesn't work anymore? What OP intended to make -will- work. Redbullusa 1580 — 9y

2 answers

Log in to vote
1
Answered by 9 years ago

You don't need that extra 'btn' in there!

Instead of doing b = math.random(1,btn[i]) Try doing b = math.random(1,i) and then to get the random gui part just do local randomButton = btn[b]

Ad
Log in to vote
1
Answered by
Redbullusa 1580 Moderation Voter
9 years ago

OBJECTIVE

To pick a random ImageButton from your GUI.

UNDERSTANDING YOUR ERROR

"math.random is expecting a number and not an object."

The math.random function accepts at most two arguments, and they both must be integers.

You must be aware that this is a table:

local btn = this.Buttons:GetChildren()

Because the :GetChildren() method fetches every child in your this.Buttons and puts it in a table.

b = math.random(1, btn[i])

So what you're doing is you're indexing/accessing the table, so you get an object instead - which is the child of this.Buttons, but what you probably intended to pass an integer.

local this = script.Parent

local btn = this.Buttons:GetChildren()
local RandomInteger = math.random(#btn) -- The minimum argument is assumed to be 1.
-- RandomInteger is a number.

local RandomButton = btn[RandomInteger]
-- Index the table with your RandomInteger (the random number).

You don't need a "for" loop, else you will iterate through ALL of the buttons when you only need 1.

Read up on arrays if you don't understand line 6.

Questions? Comments? Skepticism? Comment down below or PM me!

Answer this question