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

What is the difference between using pairs() and next() when iterating a table?

Asked by
yumtaste 476 Moderation Voter
9 years ago

NOT A SCRIPT REQUEST!!!!!!

I usually use for i, item in pairs(InsertTableHere) do when iterating through a table, but recently, I discovered that I can use next() instead of pairs() when iterating a table. I want to know what the different between pairs() and next() is. Thanks!

1 answer

Log in to vote
2
Answered by 9 years ago

There the same really,

local Table = {}

table.foreach(Table,function(v)  -- table.foreach is just like "in pairs()", but less function run time.
    print(v)
end)
==========================================================
for _,v in next, (Table) do  -- Once it prints the first data then it will move to the next
    print(v)
end
==========================================================
for _,v in pairs(Table) do -- A pair is 2, so it just prints 2 at the same time, after that it moves to the next data
    print(v)
end
0
Thanks! This will really help me with future script efficiency. yumtaste 476 — 9y
1
foreach is deprecated, so be warned about using it going forward. adark 5487 — 9y
0
True, it is deprecated. But on the other side it has less lag when it comes to function performance. MessorAdmin 598 — 9y
0
..Adark. It may be deprecated, but it is used a lot by scripters. It's much easier for me to do `table.foreach(workspace:children(), print)` than the ipairs alternative. Diitto 230 — 9y
Ad

Answer this question