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
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.
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.
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()))
@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.