Programming beginner here learning Lua. I always see this function in example code mostly in a for loop that goes through an array. I dont actually understand what it does and why I should use it. It seems I make similar for loops a lot that do almost the same thing but i never use pairs() or ipairs()
Asked
Active
Viewed 7,870 times
0
-
2Does this answer your question? [What is the difference of pairs() vs. ipairs() in Lua?](https://stackoverflow.com/questions/55108794/what-is-the-difference-of-pairs-vs-ipairs-in-lua) – aang13 Mar 15 '21 at 03:43
-
I suggest you read https://www.lua.org/pil/4.3.5.html – Nifim Mar 15 '21 at 03:44
-
"It seems I ...never use pairs() or ipairs()" Yeah, you don't have to use them, they're convenience functions. – Doyousketch2 Mar 15 '21 at 07:11
1 Answers
1
From the Lua 5.4 Reference manual:
ipairs (t)
Returns three values (an iterator function, the table t, and 0) so that the construction
for i,v in ipairs(t) do body endwill iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first absent index.
pairs (t)
If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.
Otherwise, returns three values: the next function, the table t, and nil, so that the construction
for k,v in pairs(t) do body endwill iterate over all key–value pairs of table t.
Piglet
- 27,501
- 3
- 20
- 43