Which one is better?

Option 1:

for i = 1,#Players:GetPlayers() do
            if Players:GetPlayers()[i] ~= nil  then

Option 2:

for i, player in pairs(game.Players:GetPlayers()) do
  if player ~= nil then
  • Option 1
  • Option 2

0 voters


Option 3:

local Players = game:GetService("Players")

for _, player in ipairs(Players:GetPlayers()) do
  • Option 3

0 voters

1 Like

what is ipairs? i always hear about it, never looked into it

Above this, there is a small chance that the player will leave when it is executed, so LoadCharacter would give an error.

Since it is an async function, it prefers to use pcall.

for _, player in pairs(Players:GetPlayers()) do
	local Success, Error = pcall(player.LoadCharacter, player)
	if not Success then		warn(Error)		end

warn is optional.

1 Like

The sole difference between pairs and ipairs is that ipairs was made for tables where the keys are numerical indexes (hence the extra i), and that pairs was made for dictionaries, where the keys are arbitrary.

If you were to loop through a dictionary { doggo = 1, lemonade = 2, water = 3 } with ipairs, it simply wouldn’t work (no iterations will be made).

Meanwhile, pairs works with both numerically indexed tables and dictionaries alike.

We know for sure that Players:GetPlayers returns an array (because of the documentation), so we can take advantage of that.

You may also come across a new syntax that goes like this:

for index, value in {1, 2, 3, 4} do

As you can see, both pairs and ipairs have been omitted. This is the so-called generalized iteration.

1 Like
  • pairs is like having a magic hand that can pull out one toy at a time and show it to you. It starts at the first slot, then goes to the next, and so on until it reaches the last slot. This way, you get to see all the toys in the box, but the magic hand doesn’t care about the order they are placed in.
  • ipairs, on the other hand, is like counting the toys one by one. It starts at the first slot, then goes to the next, and so on, just like counting numbers. This way, you see each toy in the order it was placed in the box.

So, in summary:

  • pairs shows you all the toys, but not in a specific order.
  • ipairs shows you all the toys in the order they were placed in the box.

Useful to note:
The ipairs iterator, is specifically designed for iterating over numeric indices in a table. This iterator is more efficient than pairs when dealing with arrays or tables that have sequential numeric keys starting from 1.

1 Like


if player then

Gets the same thing done

Please don’t do this.

When you call :GetPlayers(), you are given a table of players that are in the game. Unless you are yielding an extreme amount of time, you aren’t going to have a scenario where the player quit mid-frame. It’s an unheard problem for a reason.

This is what makes this version better … In my opinion. Myself, I like to use all predefined values vs a loops that has to re-define itself every loop.