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

pairs or ipairs could i use?

Asked by
gloveshun 119
4 years ago

i dont know what is the difference between of pairs and ipairs (and next)

local printables = {"What", 5, "blue"}
for i, v in pairs(printables) do
    print(v)
end
for i, v in ipairs(printables) do
    print(v)
end

2 answers

Log in to vote
1
Answered by
bluzorro 417 Moderation Voter
4 years ago

pairs() returns key-value pairs and is mostly used for associative tables. key order is unspecified. ipairs() returns index-value pairs and is mostly used for numeric tables. Non numeric keys in an array are ignored, while the index order is deterministic (in numeric order).

As you saw up there, pairs returns key-value pairs() while ipairs() returns index-value pairs and it's used for numeric tables (stuff that need to be printed in order and not randomly)

What next() does is literally the same as pairs() but a bit faster . I'll use your example:

local printables = {"What", 5, "blue"}

for i, v in pairs(printables) do
    print(v)
end

for i, v in next, printables do
    print(v)
end
Ad
Log in to vote
1
Answered by 4 years ago

This is a very good question, and here's the simplest I can explain it:

t will refer to local t = {"value1", "value2", nil, "value4"}

for i,v in pairs(t) do
   print("i: "..i, " v: "..v)
end

this will print

  i: 1  v: value1
  i: 2  v: value2
  i: 4  v: value3

This is probably what you'd assume this should print.

for ipairs, the difference is subtle, yet very important.

doing this same loop, but with ipairs:

for i,v in ipairs(t) do
   print("i: "..i, " v: "..v)
end

will just completely stop the loop in it's tracks at the 3rd index (nil), which means it will print this:

  i: 1  v: value1
  i: 2  v: value2

"next" functions no different than pairs, but the syntax is different:

for i,v in next,t do
    print("i: "..i, " v: "..v)
end
0
Thanks! gloveshun 119 — 4y

Answer this question