Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why is there no difference between pairs and ipairs?

Hi, from my research the gist of what I've read about pairs and ipairs is that pairs does not iterate with any determined ascending/descending order, while ipairs does. However, in practice I've tried pairs on both an array and dictionary, and simply running

local test = { john = "hey", doe = "no", yes = "oui" } for i, v in pairs(test) do print(i, v) end

prints in the same order every time. However, if I paste this exact code into an online lua compiler, it does what I'd expect - iterates with no predetermined order. Why does Roblox behave differently?

2 answers

There actually is a small difference between them

When iterating through a dictionary, the index for ipairs would not be the same as for pairs.

Here is a link that explains very well what I mean https://stackoverflow.com/questions/55108794/what-is-the-difference-of-pairs-vs-ipairs-in-lua/55109411#:~:text=pairs()%20returns%20key%2Dvalue,deterministic%20(in%20numeric%20order).

3 comments

0

Thanks for the link! That explains them giving identical outputs for arrays. What about dictionaries? The code in the original post uses a dictionary, and in an online lua compiler the output is random, but in Roblox Studio it's always the same. How come?

0

I been trying to figure out the same thing myself lol. I'm not too sure why it does that.

0

Lol, yea I'm really confused by it :( I could iterate randomly using another algorithm, but I'm still curious why it's working differently in Roblox compared to any other Lua compiler

To understand what pairs and ipairs do, you must know the difference between an array and dictionary.

An array is a numerically ordered list of key-linked values, typically appearing like this: {[1] = "First", [2] = "Second", [3] = "Third"} or without the equal signs and square bracketed numbers.

Thus, pairs is meant to check every single index/key even if its not numerically ordered while ipairs is meant for arrays and checks based on numerical index (1 until the last index/key in the array).

If you use ipairs in a mixed table (table that has both numerically ordered keys and keys that aren't numerically ordered), it will only go for those numerically ordered keys.

Thus, there is a difference. This difference is large enough to care about as well.

1 comment

0

Thank you for the explanation. In the code in the original post, though, there are no numeric leys. If you try it in Roblox Studio, pairs will output the same every time, but if you paste it into any Lua compiler, it will differ. How come? (ipairs behaves the same between Roblox/online compilers, but pairs does not)

This discussion is preserved as it was. New answers, comments, and votes are closed.