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

What are the major differences in ipairs and pairs?

Asked by 5 years ago

I know theres another post for this, but the answers there were bad in my opinion and did not cover it fully.

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

I'm glad you asked, because not many people get the concept anyway. So, what's the difference?

ipairs()

The ipairs() function will iterate through only the array part of a table, not the dictionary part. The array part of the table is the part of the table that contains indices that are not assigned to variables within the table (the dictionary part of the table is the part that holds the values assigned to variables within the table).

You would use ipairs() when you want an index from the array part of the table only:

local example = {1, 2, 3, 4, 5}
for i, e in ipairs(example) do
    print(e)
end

It gets a bit complicated from here. Lua reads the iterations of ipairs() as (table, index). That means that in our example, Lua reads (example, 1) first and (example, 5) last. Despite this, what gets printed is only the index of the table per iteration.

You can use ipairs() in Roblox when searching through the children of an Instance, which is mostly arranged as an array.

pairs()

Unlike ipairs(), which iterates only through the array part, pairs() iterates through both the array and dictionary parts of a table. Using pairs() is ideal if, of course, dealing with a dictionary.

Here's an example of using pairs() with a dictionary:

local food = {["Pizza"] = 1, ["Burger"] = 2}
for _, f in pairs(food) do
    print(f)
end

Running the above code prints the number of each key in the dictionary, but not the name of the key. If the table was in array format and we used pairs(), we would see the key names instead.

When pairs() deals with an array and a dictionary, it will print the indices in the array and the key numbers of the dictionary, but they are not guaranteed to come out in order. So, ideally, pairs() should only be used when the dictionary part of a table is not empty.

That should pretty much sum it up. If you have any questions, please ask them.

Thanks, RobloxWhizYT

Ad

Answer this question