Why doesnt math.random work?

Hello, why does this script not find a random item in the folder?

    local playersNotJoiningGameArray = {playersNotJoiningGameChildren}
			local randomPlayerIndex = math.random(1, #playersNotJoiningGameArray)
			print()
			local randomPlayerName = playersNotJoiningGameArray[randomPlayerIndex]
			randomPlayerName.Parent = playersJoiningGameFolder
			print(randomPlayerName) --table: 0x8be84c1df935964d

the output shouldve been “Decal”

math.random() isn’t really random. Why isn’t the scope for this reply (see this video from Tom Scott that explains it)

You can use the Random instance to get truly random values.

local NumberGenerator = Random.new()
local randomPlayerIndex = NumberGenerator:NextInteger(1, #playersNotJoiningGameArray)

Let me explain what this does.

NumberGenerator is set to a new Random instance. We don’t include a seed, so Roblox uses entropy to ensure it is truly random.

NextInteger returns a random integer (whole number) that is in between 1 and #playersNotJoiningGameArray.


It should also be worth noting that if playersNotJoiningGameChildren is a table- you don’t need to wrap it with curly braces.

1 Like

@ElliottLMz
Sorry, should have made this more clearly. I mean, the script doesnt even pick anything. On the print thing is this the output: [table: 0x8be84c1df935964d]

Fixed,
Somebody explain this for me. I don’t know how.

			local randomPlayerIndex = playersNotJoiningGameArray[math.random(#playersNotJoiningGameArray )
			print()
			local randomPlayerName = playersNotJoiningGameArray[randomPlayerIndex]
			randomPlayerName.Parent = playersJoiningGameFolder
			print(randomPlayerName.Parent)

Please follow category guidelines when posting:
https://devforum.roblox.com/t/about-the-scripting-support-category/45863

This will help us to help you out more easily. What exactly is not working about your code? What do you expect your code to do, and what is it in fact doing? What attempts have you made to debug it?

This is not helpful clarification. What are randomPlayerIndex and randomPlayerName equal to? This is the first thing you should be checking when debugging this code.

It looks like the problem is that playersNotJoiningGameChildren is a table, so when you declare,

local playersNotJoiningGameArray = {playersNotJoiningGameChildren}

you are nesting the table inside another table. This means that when you pick something out of that (outer) table, your code will always choose the playersNotJoiningGameChildren table itself. To solve this, you can just directly use the playersNotJoiningGameChildren table instead of playersNotJoiningGameArray.


This is totally unrelated.

7 Likes

Sorry for my bad post. Anyways, this was the answer if anyone is wondering.

1 Like

So would something like this work?

Local RandomVal = Random.new()
Local NewRandomInt = RandomVal:NextInteger(1, 10)
Print(NewRandomInt)