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

What's the difference between pairs and ipairs? [closed]

Asked by 10 years ago

I see pairs and ipairs used in for loops all the time, and they seem like they do the same thing. What's the difference?

Locked by Articulating

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

1 answer

Log in to vote
10
Answered by
Unclear 1776 Moderation Voter
10 years ago
Edited by JesseSong 3 years ago

(An edited source is manifested here)

ipairs and pairs are very similar; both of them are used to get pairs of values in tables. The biggest difference is that ipairs uses a different iterator than pairs.

So how does this affect how they function?

Well, ipairs uses an iterator that only returns pairs of values attributed to numerical keys. This means that they can only return values defined in list format. In addition, if ipairs encounters any nil value, it will stop in its tracks. Here's an example of that.

list = {1, 2, nil, 3}
for key, value in ipairs(list) do
    print(value)
end
-- 1
-- 2
-- Notice how 3 isn't printed, because ipairs encountered a nil value.

pairs, on the other hand, iterates through the entire table and returns keys that are non-numerical as well. This makes them particularly useful in dictionaries or tables with mixed entries.

Here's an example of the difference between ipairs and pairs. Take a look at the output to get a better understanding of what I'm talking about, if you had trouble grasping it.

list = {"a", "b", "c"}
dictionary = {a = 1, b = 2, c = 3}
mixed = {"a", a = 1, "b", b = 2, "c", c = 3}

function iterate(func)
    print("list")
    for key, value in func(list) do
        print(key, value)
    end

    print("dictionary")
    for key, value in func(dictionary) do
        print(key, value)
    end

    print("mixed")
    for key, value in func(mixed) do
        print(key, value)
    end
end

print("-----")
print("ipairs example...")
iterate(ipairs)

print("-----")
print("pairs example...")
iterate(pairs)
Ad