Ad
Log in to vote
2

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

Asked by 3 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.

Hi.

Looks like you're using an ad blocker.

That's fine...

No, it really is.

Just, I mean, we put a lot of work into this site, you know?

It would be really really appreciated if you would turn off your ad blocker for our website...

We tried really hard to make our ads as unobtrusive as possible.

If you really hate ads, would you consider a $2 donation via Patreon?

Here's the link.

We love you. We hope you love us too.

.

..

...

Now back to your regularly scheduled Scripting Helpers....

...

..

.

1 answer

Log in to vote
10
Answered by
Unclear 1621
3 years ago

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
Ad