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

math.random in tables aren't working?

Asked by 4 years ago

I'm trying to create a player randomizer for a game, and this is my code:

local tbl = {}
local players = game.Players:GetChildren()
table.insert(tbl, players)

print(tbl[math.random(1, #players)])

What's wrong here? The error I'm getting is: "ServerScriptService.Script:5: bad argument #2 to 'random' (interval is empty)"

2 answers

Log in to vote
1
Answered by 4 years ago
Edited by User#24403 4 years ago

You're inserting the entire group of Players, which is a table, into 'tbl'. I'm not for sure why your code is erroring that, because it's working for me, except it's printing the table id (obviously, because it's a table of Players, not an individual player).

local players = game.Players:GetPlayers()

Is already a table, there's no reason to insert it into another table; if you want to get a random player from the table, do this:

local players = game.Players:GetPlayers()

print(players[math.random(1,#players)])

0
I am just getting the same error message. thebluepicaxe717 18 — 4y
0
I updated my answer, see if adding that fixes it. invalidinvoke 134 — 4y
0
Instead of looping, you could use the PlayerAdded event and the power of the Wait method to wait until there is more than one player in the server(game.Players.PlayerAdded:Wait()). Second of all, you should not use :GetChildren() on the Players service; you should be using :GetPlayers() instead. saSlol2436 716 — 4y
0
thanks guys! it worked. thebluepicaxe717 18 — 4y
Ad
Log in to vote
1
Answered by 4 years ago

i guess you did not do wait(x) seconds, and this is the top of your script, or the script does not take much time to run.

if it is called as soon as the game starts,

local players = game.Players:GetChildren()

you have not been spawned in the game yet. so players table is empty, and the number of players will no doubtly empty.

#players

Answer this question