What is the difference between these scripts?

Hello everyone,
Just want to know the differences between these scrips:
Script 1:

	for index = 1, #AllPlots do
		if not (AllPlots[index].OwnerName.Value) then -- Plot is empty
			AllPlots[index].OwnerName.Value = player
			break
		end
	end

Script 2:

	for i, v in ipairs(plots:GetChildren()) do
		print(v.OwnerName.Value)
		if v.OwnerName.Value == nil then
			v.OwnerName.Value = player
		else
			print(v.OwnerName.Value)	
		end
	end

Thanks for the Help!

The key difference is that one uses a for i loop while the other one uses an ipairs loop. Other than that there really is not much else of a difference as they operate pretty much in the same way with the for i loop being a bit worse for readability.

oh, well I was doing a plot assigning system and Script#2 didn’t work; is it because of the ipairs?

This is true when Value is false or nil

if not (AllPlots[index].OwnerName.Value) then

This is true when Value is nil

if v.OwnerName.Value == nil then

And false is not eqal to nil, so that is the difference.

The first one is a numeric loop, which used to be faster but no longer the case. Also it breaks after iterating a nil case.

This means that if the player isnt the owner, it will stop the loop, aka other players after that player wont be able to get their ownership value assigned to them. In general the second (while written poorly) is better than the former.

The difference is that ipairs skips nil values and indexing each element might index nil but you put it a little check in both to check for nil.

Ipairs doesn’t I believe, it just stops at a nil value.

Oh, I was told it skips nil values with ipairs.

Thanks, everyone for participating and giving me your opinions, I have learned more from this!

I also made a post about questioning the difference between these loops some time ago, but I still haven’t got a clear answer as to why ipairs is best to use when iterating(or for looping an array(could be tables,list of children/descendants from :GetChildren(),:GetDescendants()))

The answer is that ipairs skips nil values and moves onto the next one.

1 Like

@Angrybirdcharacter, from what I know, ipairs skips through all nil values and paris loops through every value regardless if it is nil or not. Each function for iteration varies, so I guess there is no clear answer.

1 Like

ipairs stops looping at the first non numerical index found. It will not “jump” over and keep finding things after.

“i” = integer
pairs

Thus, numerical only iteration.

1 Like