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

Help with math.random?

Asked by 10 years ago

Every time I try to run this script I get a error saying:

Workspace.Script:16: bad argument #2 to 'random' (number expected, got nil)

Here is the output:

10

10

10

Workspace.Script:16: bad argument #2 to 'random' (number expected, got nil)

Script 'Workspace.Script', Line 16 - global SpawnRandomPostion

Script 'Workspace.Script', Line 26

Stack End

Script:

01--[[Purpose of script:
02This script is suppose to spawn a part in a random spot using the baseplate's position--]]
03------------------------Vairbles-----------------------
04BaseplatePositions= {
05BaseplateX = game.Workspace.BasePlate.Position.X,
06BaseplateY= game.Workspace.BasePlate.Position.Y,
07BaseplateZ = game.Workspace.BasePlate.Position.Z
08}
09for i,v in pairs (BaseplatePositions) do--Check
10    print(v)
11end
12------------------------Function------------------------
13function SpawnRandomPostion(X,Y,Z)
14    local Cordinates ={
15    PartX = math.random(0,X),
View all 29 lines...

Why did I get this error and how do I fix it?

If you manged to fix it show me how you did it,thank you.

1 answer

Log in to vote
5
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

The problem, as it says, is that the "second argument to math.random is nil".

That means X is nil. X was the first argument passed to SpawnRandomPosition, so that must mean that BaseplatePositions[1] is nil.

If you check that (print it out) you will in fact see that it's nil. Why?


Because the BaseplatePositions has three things in it, but none of them are at 1, 2 and 3 -- they are at "BaseplateX", "BaseplateY", and "BaseplateZ".

Thus you could fix this like this:

1RPosition =
2    SpawnRandomPostion(
3        BaseplatePositions.BaseplateX,
4        BaseplatePositions.BaseplateY,
5        BaseplatePositions.BaseplateZ)

OR you could fix this by changing the definition of BaseplatePositions to not have the BaseplateX =, etc.

You will encounter a very similar problem on line 22.

Ad

Answer this question