Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does pairs() or ipairs() do in Lua?

Tags:

lua

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()

like image 259
dyl4n130 Avatar asked Sep 03 '25 05:09

dyl4n130


1 Answers

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 end

will 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 end

will iterate over all key–value pairs of table t.

https://www.lua.org/manual/5.4/manual.html#pdf-ipairs

https://www.lua.org/manual/5.4/manual.html#pdf-pairs

like image 107
Piglet Avatar answered Sep 05 '25 01:09

Piglet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!